我试过了,但在 eval(expr, envir, enclos) 中出现错误:找不到对象“组”。pj4s 是一个包含 latlong 投影的对象。
我的代码
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"))
返回预期的内容。
那么我在哪里失败了?