Summarizing Latitude, Longitude, and Counts Data for ggplot Usage

岁酱吖の 提交于 2019-12-04 16:39:04
ako

Here is a stab with geom_hex and stat_density2d. The idea of making bins by truncating coordinates makes me a bit uneasy.

What you have is count data, with lat/longs given, which means ideally you would need a weight parameter, but that is as far as I know not implemented with geom_hex. Instead, we hack it by repeating rows per the count variable, similar to the approach here.

  ## hack job to repeat records to full count
  m<-as.data.frame(m)
  m_long <- with(m, m[rep(1:nrow(m), Count),])


  ## stat_density2d
  ggplot(m_long, aes(Lat, Lon)) + 
  stat_density2d(aes(alpha=..level.., fill=..level..), size=2, 
                 bins=10, geom=c("polygon","contour")) + 
  scale_fill_gradient(low = "blue", high = "red") +
  geom_density2d(colour="black", bins=10) +
  geom_point(data = m_long)


  ## geom_hex alternative
  bins=6
  ggplot(m_long, aes(Lat, Lon)) + 
  geom_hex(bins=bins)+
  coord_equal(ratio = 1/1)+
  scale_fill_gradient(low = "blue", high = "red") +
  geom_point(data = m_long,position = "jitter")+
  stat_binhex(aes(label=..count..,size=..count..*.5), size=3.5,geom="text", bins=bins, colour="white")

These, respectively, produce the following:

And the binned version:

EDIT:

With basemap:

map + 
  stat_density2d(data = m_long, aes(x = Lon, y = Lat,
alpha=..level.., fill=..level..), 
                 size=2, 
                 bins=10, 
                 geom=c("polygon","contour"),
                 inherit.aes=FALSE) + 
  scale_fill_gradient(low = "blue", high = "red") +
  geom_density2d(data = m_long, aes(x = Lon, y=Lat),
                 colour="black", bins=10,inherit.aes=FALSE) +
  geom_point(data = m_long, aes(x = Lon, y=Lat),inherit.aes=FALSE)


## and the hexbin map...

map + #ggplot(m_long, aes(Lat, Lon)) + 
  geom_hex(bins=bins,data = m_long, aes(x = Lon, y = Lat),alpha=.5,
                 inherit.aes=FALSE) + 
  geom_point(data = m_long, aes(x = Lon, y=Lat),
             inherit.aes=FALSE,position = "jitter")+
  scale_fill_gradient(low = "blue", high = "red")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!