在ggplot2中按多边形剪切stat_density2d图

时间:2013-05-30 20:34:39

标签: r ggplot2 visualization geospatial

我正在美国大陆绘制gdub剖面的2d密度图。 Dataframe看起来像这样:

> head(f)
    login id        location      lat       long
1 defunkt  2   San Francisco 37.78300 -122.41700
2 pjhyett  3   San Francisco 37.78300 -122.41700
3  wycats  4   San Francisco 37.78300 -122.41700
4    ivey  6 Bay Minette, AL 30.88333  -87.77694
5 evanphx  7 Los Angeles, CA 34.05000 -118.25000
6 vanpelt 17   San Francisco 37.78300 -122.41700

到目前为止,我想出了这段代码:

library(maps)
library(mapdata)
library(ggplot2)

all_states <- map_data("state")
p <- ggplot() + 
  geom_polygon( data=all_states, aes(x=long, y=lat, group = group),color="grey60", fill="white") +
  stat_density2d(data=f, aes(x=long, y=lat,fill = ..level..),geom='polygon') +
  theme(
    axis.line = element_blank(), 
    axis.text.x = element_blank(), 
    axis.text.y = element_blank(),
    axis.ticks = element_blank(), 
    axis.title.x = element_blank(), 
    axis.title.y = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    panel.background = element_blank()
  ) 

print(p)

此代码生成以下图像:

github density map usa bad graph

如何剪切超过美国边境的密度区域?

0 个答案:

没有答案