[英]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.