首页 > 解决方案 > ggplot 中的 facet_wrap 用于 SF

问题描述

library(raster)
library(ggplot2)
library(sf)

temp.shp <- getData('GADM', country='FRA', level = 2)          
temp.shp <- st_as_sf(temp.shp)  

dat <- data.frame(CC_2 = rep(temp.shp$CC_2, times = 3), 
                  value = c(sample(1:100, length(temp.shp$CC_2), replace = T),
                            sample(0.1:1, length(temp.shp$CC_2), replace = T),
                            sample(-1:-100, length(temp.shp$CC_2), replace = T)),
                  client = rep(c('a','b','c'), each = length(temp.shp$CC_2)))

 dat.shp <- merge(temp.shp, dat, by = 'CC_2')

 ggplot() +
 geom_sf(data = dat.shp, aes(fill = value), colour = NA) +
 scale_fill_viridis_c(option = 'C') + 
 facet_wrap(~client)

在此处输入图像描述

我希望每个面板都有自己的图例,因为图例范围不同

 ggplot() +
 geom_sf(data = dat.shp, aes(fill = value), colour = NA) +
 scale_fill_viridis_c(option = 'C') + 
 facet_wrap(~client, scales = 'free')

    # Error: coord_sf doesn't support free scales

标签: rggplot2sf

解决方案


获得具有单独图例的“方面”图的一种解决方案是创建三个单独的图并使用grid.arrangefrom gridExtrapackage 组装它们:

pA <- ggplot() +
  geom_sf(data = subset(dat.shp, client == "a"), aes(fill = value), colour = NA) +
  scale_fill_viridis_c(option = 'C')+
  ggtitle(label = "client a")+
  theme(plot.title = element_text(hjust = 0.5))
pB <- ggplot() +
  geom_sf(data = subset(dat.shp, client == "b"), aes(fill = value), colour = NA) +
  scale_fill_viridis_c(option = 'C')+
  ggtitle(label = "client b")+
  theme(plot.title = element_text(hjust = 0.5))
pC <- ggplot() +
  geom_sf(data = subset(dat.shp, client == "c"), aes(fill = value), colour = NA) +
  scale_fill_viridis_c(option = 'C')+
  ggtitle(label = "client c")+
  theme(plot.title = element_text(hjust = 0.5))

library(gridExtra)
grid.arrange(pA,pB,pC, nrow = 1)

在此处输入图像描述


推荐阅读