Scatter plot menggunakan ggmap dan leaflet di R

Sebenarnya ini adalah tugas kuliah yang aku tulis ulang di blog ini agar bisa menjadi bermanfaat. Memang sebenarnya akan kesulitan untuk melakukan scatter plot ke peta kemudian diterbitkan di halaman web, tetapi adanya package ggplot dan leaflet akan sangat mempermudah untuk melakukan ini. Oiya, kita akan menggunakan R-Studio sebagai IDE.

Omong-omong, sudah lama sekali sejak aku menuliskan postingan di blog ini. Sehingga aku bahkan lupa untuk login! 😀 Konyol.

Sebelum memulai langkah-langkah selanjutnya, pastikan kamu sudah memiliki API Key untuk Google Maps.

Memuat peta King County dengan ggmap

Pada kasus ini kita akan coba menggunakan dataset House Sales in King County dari situs Kaggle. Dataset ini memiliki sekitar21613 pengamatan dengan 19 fitur. Dataset ini memiliki fitur longitude dan latitude yang akan menjadi koordinat di peta yang akan kita buat.

Pertama kita muat dulu dataset dalam format berkas csv.

rawdataset = read.csv2(file = "/home/bit/git/kuliah/dm/kc_house_data.csv", header = TRUE, sep = ",", dec = ".")

Kemudian seperti biasa, salin dulu variabelnya. Entahlah, ini lebih seperti kebiasaan daripada keharusan. Karena dengan ini, akan lebih mudah untuk mendapatkan salinan dataset yang belum diubah tanpa harus memuat ulang dengan perintah read.csv.

dataset=rawdataset

Kemudian masukan API Key untuk Google Maps, dan yang paling penting, muat package ggmap.

key = "AIzaSyBFvLBsSqNZ2p3ZsorjbtK8SB0ZyTbJMLA"
library("ggmap")

Setelah itu kita buat minimum bounding box (disebut pula sebagai bbox) pada peta King County. Kemudian dengan bbox ini, kita dapatkan irisan peta dunia pada wilayah King County saja.

ssbox = make_bbox(lon=dataset$long, lat=dataset$lat, f=0.1)
sq_map=get_map(location=ssbox, maptype = "roadmap", source="google", api_key = key)

Kemudian peta ini dapat langsung ditampilkan menggunakan ggmap

ggmap(sq_map)

Menyiapkan cluster harga rumah

Sebenarnya kita bisa langsung membuat plot posisi rumah pada peta tanpa melakukan clustering (pengelompokan) harga, tetapi informasi yang ditampilkan hanyalah posisi. Kita dapat berkreasi dengan mewarnai titik sesuai dengan kelompok harga rumah. Oleh karena itu, pertama kita buat lebih dahulu kelompok harga rumah. Kamu tentu saja bisa melakukan pengelompokan atau pengkelasan sesuai metode yang diinginkan. Saya untuk percobaan ini menggunakan algoritma kmeans. Walaupun temanku menyarankan menggunakan kmedoid untuk mengurangi dampak data pencilan.

Karena dataset tidak diurutkan berdasarkan harga, maka kita urutkan terlebih dahulu. Kemudian buat scatter plot dari harga terurut.

dataset= dataset[order(dataset$price),]
plot(dataset$price, type="o", cex=0.5)

Plot diatas kelihatannya susah dimengerti karena kurangnya keterangan penjelas. Tetapi masih dapat dimengerti bahwa sumbu X adalah index rumah yang sudah terurut dan sumbu Y adalah harga rumah. (Ya! Aku tahu ini jelek, seharusnya ada cara yang lebih baik daripada membuat plot dengan cara ini!)

Setelah itu kita lakukan pengelompokan berdasarkan harga rumah, kemudian kita tarik garis dimana pusatnya.

clusterharga = kmeans(x = dataset$price, centers = 5)
dataset$cluster = clusterharga$cluster
abline(h=clusterharga$centers, col="red")

Tadaaa! Garis merah menunjukkan 5 pusat kelompok harga. Dari situ kita lakukan binning terhadap masing-masing kelompok.

Binning

Setelah didapatkan kelompok-kelompok harga rumah, maka perlu dicari batas atas masing-masing kelompok. Batas tersebut nantinya akan digunakan untuk proses binning.

clusterupperlimit = sort(c(
max(dataset[dataset$cluster==1, "price"]),
max(dataset[dataset$cluster==2, "price"]),
max(dataset[dataset$cluster==3, "price"]),
max(dataset[dataset$cluster==4, "price"]),
max(dataset[dataset$cluster==5, "price"])
))

Jika kamu tahu cara melakukan iterasi kode diatas, silakan tinggalkan komentar. Setelah itu, kita bisa lihat batas atas dari masing-masing cluster dari variabel clusterupperlimit. Selanjutnya adalah proses binning dan gabungkan hasilnya dengan dataset.

breaks = c(-Inf, clusterupperlimit[1], clusterupperlimit[2], clusterupperlimit[3], clusterupperlimit[4], Inf)
labels = c("$", "$", "$$", "$$", "$$$")
bins = cut(x = dataset$price, breaks = breaks, labels = labels, include.lowest = TRUE, right = FALSE)
dataset <- cbind(dataset, bins)

Hasil binning tersebut bisa kita lihat dengan summary(bins) atau plot dengan ggplot.

ggplot(data=dataset, aes(x=dataset$bins,fill=..count..)) + 
geom_bar(color='black', alpha=0.9) + 
stat_count(geom="text", aes(label=..count..), hjust=-0.1) +
theme_bw() + 
labs(y="Number of Houses",x="Count") +
coord_flip() +
ylim(0,25000) +
scale_x_discrete(drop=FALSE)

Kita sudah dapatkan peta dan juga kelompok harga, langkah terakhir adalah melakukan plot ke peta.

Peta tersebut bisa disimpan dengan mealui fungsi eksport atau menggunakan perintah ggsave.

Publikasi peta ke web dengan leaflet

Jika hanya menyimpan peta ke komputer, maka langkah sebelumnya sudah cukup. Tetapi, kali ini kita ingin lebih. Dengan mempublikasi peta dengan leaflet, maka peta yang dihasilkan akan lebih interaktif. Apalagi jika kamu adalah pengembang web yang sudah biasa dengan javascript.

Pertama kita muat library dan salin dulu petanya, seperti biasa.

library("leaflet")
library("dplyr")
library("htmlwidgets")
mapdata=dataset

Kemudian karena warna yang dihasilkan ggmap terlalu cerah dan norak, kita bisa cari di internet color pallette yang lebih sedap dipandang. Beruntung saya menemukannya di sini: 36 Beautiful Color Palettes For Your Next Design Project.

colorpallete=c("#7bc043", "#0392cf", "#fdf498", "#f37736", "#ee4035")
colorlabel=c("$", "$", "$$", "$$", "$$$")
color=colorFactor(palette = colorpallete, domain = colorlabel)

Kemudian untuk menambahkan info popup ke peta yang akan dibuat, maka kita susun dahulu data yang akan kita tampilkan

mapdata % > % mutate(info=paste( " <table> <tr> <th colspan=>Information</th> </tr> <tr> <td>Class</td> <td colspan=>",bins,"</td> </tr> <tr> <td>Price</td> <td>",price/1000,"</td> <td>K USD</td> </tr> <tr> <td>Bedrooms</td> <td colspan=2>",bedrooms,"</td> </tr> <tr> <td>Bathrooms</td> <td colspan=2>",bathrooms,"</td> </tr> <tr> <td>Lot</td> <td>",sqft_lot,"</td> <td>ft2</td> </tr> <tr> <td>Living Lot</td> <td>",sqft_living,"</td> <td>ft2</td> </tr> </table> " )) -> mapdata

Setelah itu, dibuat peta menggunakan leaflet.

kingcountymaps=leaflet(data = mapdata) % > % addProviderTiles("OpenStreetMap.DE") % > % addCircleMarkers(lng = ~long, lat = ~lat, radius = 1.5, color = ~color(bins), stroke = FALSE, fillOpacity = 0.9, popup = ~info ) % > % addLegend("bottomright", colors= colorpallete, labels=colorlabel, title="Price cluster")

Kamu bisa melihat langsung peta yang telah dibuat ini dengan mengetikkan kingcountymaps di console.

Setelah semua beres, maka saatnya mengekspor petaya yang kita buat ke web dengan bantuan widgetmaker.

saveWidget(widget = kingcountymaps, file = "kingcounty.html", selfcontained = FALSE, title = "King County House Price Cluster")

Maka dihasilkan berkas html dan library pendukungya. Berkas ini disimpan di working directory yang telah kamu set.

Selanjutnya unggah berkas tersebut ke web kamu. Hasil yang aku buat bisa kamu lihat di sini: King County House Price Cluster. Aku yakin peta yang kamu buat akan lebih indah, oleh karena itu jangan lupa tinggalkan jejak di komentar.

Tambahan

1. Working directory bisa kamu atur dengan mudah melalui perintah

setwd("<path_to_folder>")

2. Peta dasar leaflet dapat diubah pada fungsi addProviderTiles Contoh peta yang tersedia ada pada Leaflet Provider Demo.

addProviderTiles("OpenStreetMap.DE")

3. Info pop-up dapat mengandung html, termasuk tabel. Oleh karena itu kamu bisa buat template-nya menggunakan tool HTML Table Generator.

How Do People Get Rich?

I admit that indeed, the concept of a wealth is difficult to understand. Wealth distinguishes us from others and turns the palms upside down. The key is knowing where and how the money flows. That distinguishes the rest of us from the rich. That’s why the rich are on holiday Austria, while the rest are wrestling in front of the computer. Let my humble writing tell you a bit.
Continue reading How Do People Get Rich?

The Most Common Grammar Mistakes in English

Language is one of the products of a community that sometimes has flexible rules that not everyone can understand. Sometimes the flexibility of the language itself makes people break some of the basic rules of language syntax. Errors in grammar generally occur and are not realized. Continue reading The Most Common Grammar Mistakes in English

Best Thing to Buy on Thanksgiving, Black Friday, and Cyber Monday 2017!

At the end of the year, a lot of events that give a lot of discounts. Instead of saving money, Black Friday, Thanksgiving, and Cyber Monday will instead spend more money than any other day. But, if you’re smart, you have to manage what to buy that day. To get the best deal, customers even have to look around the corner of the store. Is this holiday the best time to buy something you want? What is the best thing to buy?

Yes! Short holiday! We do not want to wait another year to buy something cheap. DealNews has analyzed the items that became the big deal to buy on year-end holidays. Then, it should be understood that items that are not listed here may be more valuable elsewhere. Use the list below just as a guide to finding your best deal this year! And do not forget to see the list of stores that are predicted to open that I’ve got here.

The Best Thing to Buy on Thanksgiving, Black Friday, and Cyber Monday.

 ThanksgivingBlack FridayCyber Monday
Electronic
Android
Cameras
Headphones
iPhones
Speakers
TVs
Computers
Data Storage
iPads/Tablets
Laptops
Entertaiment
Movies, etc/
Toys
Travel
Video Games
Home & Garden
Appliances
Kitchen
Tools
Beauty
Cloting
Shoes
Beauty

Best things to buy on Thanksgiving -> Smartphone!

Android smartphone with a headset
Android smartphone with a headset

Last year, we could know that fitting the day before Black Friday, mobile phone sales reached a profit (via gift cards). Although the total number of deals on Thanksgiving and Black Friday is not much different, the recommendations remain on Thanksgiving. This is because, in 2012, 42{2b74503c6d54fbb70c5b6b7318afd0dccb2199033ff1b0afa192bc55eb8e68dc} of mobile phone sales happened on Thanksgiving, while 32 percent can be achieved on Black Friday. In fact, 50{2b74503c6d54fbb70c5b6b7318afd0dccb2199033ff1b0afa192bc55eb8e68dc} more Android sales happen during Thanksgiving. But not for iPhone.

Best things to buy on Black Friday -> Laptop!

White Acer Chromebook
White Acer Chromebook

At this year’s Black Friday, Chromebooks are estimated to be around $ 99, bargain laptop doorbusters for $ 110, and mainstream machines can be pushed below $ 300. Last year, Dell Inspiron Celeron 1.6Ghz 11 “laptop has a price of $ 100 onThanksgivingg.This year on the Black Friday, Chromebook with 2.16Ghz Celeron Processor, 2GB of RAM and a 16GB SSD will go to $ 99.

Black Friday is also a perfect time to take advantage of low-cost hard drives, USB flash drives, and memory cards. On average, Black Friday boasted 33{2b74503c6d54fbb70c5b6b7318afd0dccb2199033ff1b0afa192bc55eb8e68dc} more storage deals than Thanksgiving and almost 85{2b74503c6d54fbb70c5b6b7318afd0dccb2199033ff1b0afa192bc55eb8e68dc} more than Cyber Monday.

Best Things to Buy on Cyber Monday -> Clothes!

Clothing rack by Parker Burchfield
Clothing rack by Parker Burchfield

On the past two Cyber Mondays, 45{2b74503c6d54fbb70c5b6b7318afd0dccb2199033ff1b0afa192bc55eb8e68dc} more deals happen on Black Friday, and about 53{2b74503c6d54fbb70c5b6b7318afd0dccb2199033ff1b0afa192bc55eb8e68dc} more deals than on Thanksgiving. While it’s tends to be overshadowed by Black Friday and Thanksgiving, Cyber Monday is the perfect time to grab the sweetest you can. Eh, do you want a baked egg?

Originally posted on DealNews and LifeHacker.

How to Delete an Instagram Account Permanently / Temporarily

Instagram is an extraordinary phenomenon that ever happened. I used to use it for a few hours a day! I feel empty. Once thought, it looks like Instagram is time-consuming. Therefore, some time ago I temporarily stopped my Instagram account. I did not delete it permanently because I want to save its username. hehehe If you want to try to permanently or temporarily erase your Instagram account, follow the steps below: Continue reading How to Delete an Instagram Account Permanently / Temporarily

How to Take A Screenshot on Any Computer or Smartphone

How to take a screenshot. Many things are actually very easy to do, but most people do not know. Have you ever done a screenshot? Some devices have screenshot mechanisms that are different from each other, but some are the same. Here is a quick list how to screenshot:

Continue reading How to Take A Screenshot on Any Computer or Smartphone

Top Ten Most Beautiful Nature Spots In Austria You Will Never Visit

This is an old post from old cubicless entertaiment site.

Be honest, not all of us born rich or have decent work. So, traveling around the world is kinda impossible. Don’t worry, I found these top ten most beautiful nature sport in Austria from this site. You might download them and set them as wallpaper.

 “Zey call it O-s-t-e-r-r-e-i-c-h!” –  Bertrand R. Brinley

Austria tourism has been full of breathtaking nature. Snow covered mountains, mysterious fairy forest (really?), and lakes will bring you to next level of excitement. Enjoy…

1. Hintersee

Hintersee
Hintersee from www.touraustriavienna.com

2. Vilsalpsee

Vilsalpsee
Vilsalpsee from www.touraustriavienna.com

3. Kaunergrat Tyrol

Kaunergrat Tyrol
Kaunergrat Tyrol from www.touraustriavienna.com

4. Lake Schlegeis

Lake Schlegeis
Lake Schlegeis from www.touraustriavienna.com

5. Gosausee Lake

Gosausee Lake
Gosausee Lake from www.touraustriavienna.com

6. Reutte, Tyrol

Reutte, Tyrol
Reutte, Tyrol from www.touraustriavienna.com

7. Speicher Durlassboden

Speicher Durlassboden
Speicher Durlassboden from www.touraustriavienna.com

8. Amphitheater, Tyrol

Ampitheater, Tyrol
Amphitheater, Tyrol from www.touraustriavienna.com

9. Schlegeis reservoir

Schlegeis reservoir
Schlegeis reservoir from www.touraustriavienna.com

10. Hallstatt

Hallstatt
Hallstatt from www.touraustriavienna.com

That’s All!

Thanks for stopping by, if you interested in traveling to one of these places above, you can contact Austria Tourism. Ironically, their contact page looks like this:

Austria Tourism's contact page
Austria Tourism’s contact page error. Why?

Someone, please tell them!

What are the best one-minute life hacks that work?

One minute is a short time. But not for cool people. Here’s a list of the best one-minute life-hacks I’ve chosen from various websites and my own experience!

1. Talk to yourself when you get into trouble

Bassam Atheeque said that one of the best one-minute life hacks he learned from reading one of Dale Carnegie’s  books “How to Stop Worrying & Start Living”.

dale carnegie secrets of success
Quora

  • Want to answer teacher questions, but difficulties for initiative? Afraid of wrong?

Think about the worst. Of course, your teacher will not throw stones at you. No one will burn your house and kill your dog. The worst possibility is that you are laughed at in the classroom a few minutes, then all is gone.
Another possibility is that your answer is correct, and everyone applauds. Another possibility is that you can throw questions to your other friends
But now you feel in a position where no one person has the guts to do what you do. You are a hero!

  • A red mark in the exam answers?

The only possible worst is that the red mark will remain forever in the paper. But who cares?
It will not make you forever unemployed until the end of your life. In fact, almost everyone has done it. And they’re fine.

  • Wanna propose that damn pretty girl of your group you have been dreaming for centuries but scared of getting rejected?

Just say it.
He will not slap you in public or water you with warm coffee. It just happens to “reality show” on tv. The worst possibility is she will say ““I thought you as my friend” and she might feel dejected. But it will not be forever. Time heals and she will get normal again!

2. Temporal Focus

Pen tip from macro shoot
Pen tip from macro shoot | naghtigall via Pixabay

It’s not one-minute life hacks because if you do this more than 60 seconds, your head will strain. The first time, I think I’m the only one doing this. Apparently, there are others too. Before I started learning, I used to focus on seeing small things. Literally. Pencil tip, door knobs, nail tip, and so on.
The steps are very easy:
1. Take a pencil or pen.
2. Hold with your hands straight. Or like Rishabh Singh said, 30cm from your eyes.
3. See the tip of the pencil, down to the detail. Black dots.
4. And most important, do not think.

Not difficult, but also not easy. Do this every day to practice concentration.

3. One Two-Minute Rule

Running cheetah
Running cheetah| Photo by Cara Fuller on Unsplash

This is not a one-minute life hack, but it is really helpful. If you do not know if something should be done, estimate the time it takes to do it. If it takes more than 2 minutes, you may postpone it. But if it takes less than 2 minutes, quickly do before thinking about anything.
This works out at me, let me know how about you.

4. Schedule your procrastination

Procrastination is not bad if it is planned. Knowing when to work and when to laze is important. The absence of rewards to oneself can dampen morale. Even some great ideas can be found when the brain is relaxed. Try to plan your lazy time, buddy!

5. Do not think

Thinking about something that is not important is like turning on a computer for days but not in use. Stop thinking about something that is not important, such as which route to take, just walk! (Unless time is very, very urgent!). Some geniuses even wear the same clothes every day, having the same clothes in the closet.

6. Stop Wasting Your Hard-Earned Free Time

See this post about Stop Wasting Your Hard-Earned Free Time. But in short,

“It is not that we have a short time to live, but that we waste a lot of it. Life is long enough, and a sufficiently generous amount has been given to us for the highest achievements if it were all well invested.” – On the Shortness of Life

Bonus: Another One-minute life hacks

Colored chair
Rotterdam’s Kunsthal Chair | Photo by Thomas Rusling on Flickr

I do this every day while studying in class. Sitting in front will be very helpful to always focus. If sitting in a circle, sit as close as possible to someone who has a higher position. People tend to feel uncomfortable to do “bad things” to people nearby.