![](/img/trans.png)
[英]Issues plotting a combined shapefile in R using ggplot, no defined error given
[英]Plotting a grid data on a map using a shapefile with ggplot in R
我想使用ggplot在世界地图上绘制网格数据。
这是我在这篇文章之后尝试的内容: R在地图上绘制网格值 ,但出现错误。
数据:
require(maptools)
nasafile <- "http://eosweb.larc.nasa.gov/sse/global/text/global_radiation"
nasa <- read.table(file=nasafile, skip=13, header=TRUE)
然后,我加载了从此处下载的shapefile: http : //www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_land.zip
shapef <- readShapeLines(fn = "shapefiles/ne_110m_land.shp")
因为稍后我想使用geom_scatterpie
函数,所以我将要绘制的Ann
值转换为因子并制作了调色板。
nasa$Annf <- as.factor(as.character(nasa$Ann))
mypalette <- colorRampPalette(brewer.pal(9,"YlOrRd"))(533)
然后我使用ggplot绘制了数据:
ggplot(aes(y = Lat , x = Lon), data = nasa )+
geom_tile(aes(fill=Annf)) +
guides(fill=FALSE) +
geom_path(data = shapef) +
scale_fill_manual(values = mypalette) +
theme_void() +
coord_equal()
但是我得到这个错误: Error in eval(expr, envir, enclos) : object 'Lon' not found
错误: Error in eval(expr, envir, enclos) : object 'Lon' not found
即使Lon
列出现在我的数据框中:
head(nasa)
Lat Lon Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Ann Annf
1 -90 -180 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19
2 -90 -179 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19
3 -90 -178 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19
4 -90 -177 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19
5 -90 -176 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19
6 -90 -175 9.63 5.28 0.75 0 0 0 0 0 0.1 3.24 8.28 10.97 3.19 3.19
我想要的输出将是在shapefile定义的地图顶部绘制Annf
值,该文件仅是大陆的表面。
你有经度纬度和列nasa
,但不shapef
。 在ggplot中使用后者之前,必须先增强后者。
尝试更换线
geom_path(data = shapef) +
与此相反:
geom_path(data = fortify(shapef), aes(x=long, y=lat, group=group)) +
编辑:
您的geom_tile()层覆盖整个图。 因此,如果仅希望将其显示在陆地上,则需要覆盖海洋。
问题1 :覆盖海洋
土地的shapefile包含土地块的多边形,而不是海洋。 为了获得可以遮盖大海的多边形,我从同一网站( http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_ocean.zip )获得了多边形:
shapef.sea <- readShapePoly(fn = "ne_110m_ocean.shp")
问题2 :shapefile中的孔
由于有被陆地完全包围的陆地(例如,澳大利亚),所以海洋shapefile包含中间带有“孔”的多边形,并且ggplot不能很好地处理孔(在此处的文档中讨论)。
幸运的是, ggpolypath软件包正是为此目的而创建的。
require(ggpolypath)
ggplot(aes(y = Lat , x = Lon), data = nasa) +
geom_tile(aes(fill=Annf)) +
guides(fill=FALSE) +
geom_polypath(data = fortify(shapef.sea), aes(x=long, y=lat, group=group), fill = "steelblue2") +
geom_path(data = fortify(shapef), aes(x=long, y=lat, group=group)) +
scale_fill_manual(values = mypalette) +
theme_void() +
coord_equal()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.