繁体   English   中英

facet_wrap 在 ggplot for sf

[英]facet_wrap in ggplot for 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

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

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)

在此处输入图片说明

您也可以考虑使用tmap包。 这是一个可能的解决方案:

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

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

tm_shape(dat.shp) + 
    tm_polygons("value", palette = "viridis") +
    tm_layout(legend.position = c("left", "bottom")) +
    tm_facets("client", free.scales = TRUE) 

reprex 包(v0.3.0) 于 2020 年 3 月 12 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM