[英]ggplot2; Adding points from a different dataset and a raster/matrix data to a plot of a spatialpolygonsdataframe
我尝试了这个,但是我在eval(expr,envir,enclos)中遇到错误:找不到对象'group'。 pj4s是一个包含拉特隆投影的对象。
我的密码
fx.ggplot<-function(ctry,aesfill="id",scalefill="Country",pathcol="white"){
#ctry is a shapefile of countries
ctry@data$id = rownames(ctry@data)
ctry.points = fortify(ctry, region="id")
ctry.df = join(ctry.points, ctry@data, by="id")
(txt<-paste("p<-ggplot(ctry.df) + aes(long,lat,group=group,fill=",aesfill,")"))
eval(parse(text=txt))
p<-p+ geom_polygon() +
geom_path(color=pathcol) +
coord_equal() +
scale_fill_brewer(scalefill)
return(p)
}
#generate a grid of points
xo<-seq(25,45,0.5)
yo<-seq(-15,5,0.5)
head(xy<-cbind(expand.grid(xo,yo)));names(xy)<-c("lon","lat")
head(xy.sp <- SpatialPoints(xy,proj4string=pj4s))
Overlay<-over(xy.sp,ctry)
xy<-xy[!apply(Overlay, 1, function(x) any(is.na(x))),]
#plot
(p<-fx.ggplot(ctry))
(P<-p+geom_point(data=xy, aes(x=lon, y=lat))) #addpoints returns Error
ggplot()+geom_point(data=xy, aes(x=lon, y=lat)) #This plots the points (as below) without error but in a new plot.
#matrix
mat.ctry<-fx.polygon2raster2array(shp=ctry,xo,yo,cTim=1)
mat<-cbind(expand.grid(xo,yo),c(mat.ctry));names(mat)<-c(names(xy),"Z")
mat<-mat[!apply(mat, 1, function(x) any(is.na(x))),]
p+geom_raster(data=mat,aes(x=lon,y=lat,colour="red"))
#returns错误,但ggplot()+geom_raster(data=mat,aes(x=lon,y=lat,colour="red"))
返回预期的结果。
那我哪里失败了?
万一其他人无法为他们得到公认的答案:关键是@aosmith在原始问题的评论中指出的内容。
添加geom_point(data=xy)
在绘图上创建一个新层。 ggplot2
希望该新层与原始层的所有美感相匹配,因此您必须专门定义任何差异。 在这种情况下,原始的geom_polygon
图层使用group
fill
美学,但geom_point
图层则不使用。 因此,必须为geom_point
指定group=NULL
和fill=NULL
,如下所示:
(myplot + geom_point(data=xy, aes(group=NULL, fill=NULL)))
让我们分解正在发生的事情并修复一些问题。 首先,为代码/示例加载必要的库。
library("rgeos")
library("sp")
library("ggplot2")
library("plyr")
查看您的示例地图,我找出了您拥有哪些东非国家。 我从rworldmap
包中提取了形状文件。 这些可能不如您的形状文件好,但是现在它们会做。
library("rworldmap")
data(countriesLow)
ctry <- countriesLow[countriesLow$ISO3.1 %in% c("TZA", "KEN", "UGA", "RWA", "BDI"),]
创建您拥有的点的网格。 我整理了一些代码,放弃了对head
调用,并简化了子集代码。
#generate a grid of points
xy<-expand.grid(long=seq(25,45,0.5),lat=seq(-15,5,0.5))
xy.sp <- SpatialPoints(xy, proj4string=CRS(proj4string(ctry)))
Overlay<-over(xy.sp,ctry)
xy<-xy[!is.na(Overlay$ISO3.1),]
现在,您的fx.ggplot
调用可以重写为
fx.ggplot<-function(ctry, aesfill="id", scalefill="Country", pathcol="white") {
##ctry is a shapefile of countries
ctry@data$id = rownames(ctry@data)
ctry.points = fortify(ctry, region="id")
ctry.df = join(ctry.points, ctry@data, by="id")
ggplot(ctry.df, aes(long, lat)) +
geom_polygon(aes_string(group="group", fill=aesfill)) +
geom_path(colour = pathcol) +
scale_fill_brewer(scalefill)
}
总体aes
long
而lat
; geom_polygon
需要附加的美学group
和fill
,并且使用aes_string
设置aes_string
因为将fill变量的名称传递到函数中。
(p <- fx.ggplot(ctry))
这个版本中有一些工件,但是(可能)是我使用的形状文件。 在您显示的情节中我没有看到它们,因此您应该不会有任何问题。
p + geom_point(data=xy)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.