簡體   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