使用stat_binhex在地图上的六角形热图给出错误:geom_hex()仅适用于笛卡尔坐标

时间:2015-12-30 08:36:12

标签: r ggplot2 ggmap

我试图用定位数据的六边形热图覆盖地图(stat_binhex + ggmap)。我可以使用基于正方形的热图(stat_bin2d + ggmap)到达那里,但我认为六边形变体更好。

我得到了

  

错误:geom_hex()仅适用于笛卡尔坐标

stat_binhex可以与我的经度和纬度坐标一起使用,只要我不将它与地图相结合(参见代码)。

这是我可重复的例子:

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

这是我的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 

1 个答案:

答案 0 :(得分:7)

这个怎么样:

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

也许这对于进一步的工作会更好。

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