R:为多个 shapefile 制作通用图例和配色方案

R: Making common legend and colour scheme for multiple shapefiles

首先是示例数据:

library(raster)
# download a sample shape file
shape.file <- getData('GADM', country='FRA', level=2)

ID_2 <- rep(shape.file@data$ID_2,times=2)
group.id <- rep(c(100,200),each=96)

set.seed(1)
cat1<- runif(192,min=0,max=100)
set.seed(2)
cat2<- runif(192,min=0,max=100)
set.seed(3)
cat3<- runif(192,min=0,max=100)

dat <- as.data.frame(cbind(ID_2,group.id,cat1,cat2,cat3))

# extract the data for group.id = 100 and group.id = 200 in two seprate df

group.id.100 <- dat[dat$group.id==100,]
group.id.200 <- dat[dat$group.id==200,]

# merge with shape file

merge.shp.100 <- merge(shape.file,group.id.100, by="ID_2") 
merge.shp.200 <- merge(shape.file,group.id.200, by="ID_2") 

# plot them together 
par(mfrow=c(3,2))

plot(merge.shp.100,col=merge.shp$cat1,main="Group.id.100,cat1")
plot(merge.shp.100,col=merge.shp$cat2,main="Group.id.100,cat2")
plot(merge.shp.100,col=merge.shp$cat3,main="Group.id.100,cat3")

plot(merge.shp.200,col=merge.shp$cat1,main="Group.id.200,cat1")
plot(merge.shp.200,col=merge.shp$cat2,main="Group.id.200,cat2")
plot(merge.shp.200,col=merge.shp$cat3,main="Group.id.200,cat3")

我想为所有 6 个数字插入一个共同的图例和配色方案。 例如,图例应该从 minimum = min(c(cat1,cat2,cat3))max(c(cat1,cat2,cat3)) 对于所有六个数字。同样,值 50 应该在所有 6 个数字中具有相同的颜色。

谢谢

您可以使用spplot

示例数据:

library(raster)
s <- getData('GADM', country='FRA', level=2)[, c('GID_1', 'NAME_1', 'GID_2', 'NAME_2')]       
set.seed(1)
m <- matrix(runif(96*6, 0, 100), nrow=96, ncol=6)
vars <- paste0("cat", 1:6) 
colnames(m) <- vars
d <- data.frame(GID_2 = s$GID_2, m)
sd <- merge(s, d)

使用 spplot:

spplot(sd, vars)

有了底图,你可以做类似的事情

brks <- seq(0,100,20)
par(mfrow=c(2,3), mai=c(0,0,0.5,0))
cols = rainbow(length(brks))
for (v in vars) {
    cuts <- cut(data.frame(sd)[, v], brks)
    plot(s, col=cols[cuts], main=v)
}