Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexagonal heatmap on map with stat_binhex gives error: geom_hex() only works with Cartesian coordinates

Tags:

r

ggplot2

ggmap

I'm trying to overlay a map with a hexagonal heatmap of positioning data (stat_binhex + ggmap). I can get there with a square based heatmap (stat_bin2d + ggmap) but I think the hexagonal variant is nicer.

I get

Error: geom_hex() only works with Cartesian coordinates

The stat_binhex does work with my longitude and latitude coords as long as I don't combine it with a map (see code).

Here is my reproducible example:

library(ggplot2)
library(ggmap)

#set center coordinates
center_longitude<--73.963895
center_latitude<-40.7727524

#define map
map <- get_googlemap(center=c(center_longitude,center_latitude), scale = 2,zoom=12)

#test map in plot
ggmap(map)

#simulate some coordinates deviating from the central points
coords<-data.frame(longitude=rnorm(10000, mean = center_longitude, sd = 0.003),
                   latitude=rnorm(10000, mean = center_latitude, sd = 0.003))

#Plot longitude and latitude coords with stat_binhex but no map, this works
plt<-ggplot()+
  stat_binhex(data=coords,aes(x=longitude,y=latitude))
plt

#I now try to overlay this on the map but this doesn't work
plt2<-ggmap(map)+
  stat_binhex(data=coords,aes(x=longitude,y=latitude))
plt2

#Error: geom_hex() only works with Cartesian coordinates

#a square based heatmap on a map does
plt3<-ggmap(map)+
  stat_bin2d(data=coords,aes(x=longitude,y=latitude))
plt3

This is my sessioninfo:

R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=Dutch_Belgium.1252  LC_CTYPE=Dutch_Belgium.1252    LC_MONETARY=Dutch_Belgium.1252 LC_NUMERIC=C                  
[5] LC_TIME=Dutch_Belgium.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggmap_2.6     ggplot2_2.0.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.2         magrittr_1.5        maps_3.0.1          munsell_0.4.2       colorspace_1.2-6    geosphere_1.5-1    
 [7] lattice_0.20-33     rjson_0.2.15        jpeg_0.1-8          stringr_1.0.0       plyr_1.8.3          tools_3.2.3        
[13] grid_3.2.3          gtable_0.1.2        png_0.1-7           digest_0.6.8        RJSONIO_1.3-0       mapproj_1.2-4      
[19] reshape2_1.4.1      labeling_0.3        sp_1.2-1            stringi_1.0-1       RgoogleMaps_1.2.0.7 scales_0.3.0       
[25] hexbin_1.27.1       proto_0.3-10 
like image 930
Jeroen Boeye Avatar asked Jan 06 '23 22:01

Jeroen Boeye


1 Answers

How about this:

ggmap(map) +
coord_cartesian() +
stat_binhex(data=coords,aes(x=longitude,y=latitude))

Maybe this will be better for further works.

ggmap(map, base_layer = ggplot(coords, aes(x=longitude, y=latitude))) +
coord_cartesian() +
stat_binhex()
like image 143
skwon Avatar answered Jan 28 '23 19:01

skwon