Search code examples
rcolorsrastershapefiler-sp

R: Making common legend and colour scheme for multiple shapefiles


A sample data first:

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")

enter image description here

I want to insert a common legend and colour scheme for all the 6 figures. For example, the legend should go from minimum = min(c(cat1,cat2,cat3)) to max(c(cat1,cat2,cat3)) for all the six figures. Similarly, a value of 50 should have the same colour in all the 6 figures.

Thank you


Solution

  • You can use spplot

    Example data:

    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)
    

    Use spplot:

    spplot(sd, vars)
    

    spplot

    With base plot, you could do something like

    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)
    }
    

    base plot maps