Thinh Huynh (Huynh Cong Thinh) - Blog

Microsoft MVP, Data Scientist & Cloud Architect

Plot long/lat geography data to Google Maps in R

Just a quick note.
Will be updated with detailed explanation later.

Input data: data.txt includes latitude, longitude coordinates

10.7187673	106.5551385
10.7958682	106.6801612
10.8486773	106.6014845
10.7599045	106.6896963
10.7992661	106.6879919
10.7096651	106.6018989
10.8440446	106.6361442
10.7993318	106.6474135
10.6217157	106.6861033
...

Read data.txt

longlat <- read.table("data.txt", sep = "\t", quote = "", strip.white = FALSE, blank.lines.skip = TRUE, header = F)

R code:

library(ggplot2)
library(ggmap)

########### download map
mapgSG <- get_map(location = c(lon = mean(longlat$long), lat = mean(longlat$lat)), zoom = 12, maptype = "roadmap", scale = 2)
########### data point
ggmap(mapgSG) + geom_point(data = longlat, aes(x = long, y = lat, fill = "red", alpha = 0.8), size = 1.5, shape = 21) + guides(fill=FALSE, alpha=FALSE, size=FALSE)

Output: Data points on Google maps

saigon_longlat

How about heatmap visualization:

ggmap(mapgSG, extent = "device") + geom_density2d(data = longlat, aes(x = long, y = lat), size = 0.3) + stat_density2d(data = longlat, aes(x = long, y = lat, fill = ..level.., alpha = ..level..), size = 0.01, bins = 16, geom = "polygon") + 
             scale_fill_gradient(low = "green", high = "red") + 
             scale_alpha(range = c(0, 0.3), guide = FALSE)

Output:
Saigon Heatmap