facet_wrap в ggplot для sf - PullRequest
       14

facet_wrap в ggplot для sf

1 голос
/ 03 марта 2020
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)

enter image description here

Я хочу, чтобы у каждой панели была своя легенда, поскольку диапазон легенд различен

 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

Ответы [ 2 ]

1 голос
/ 03 марта 2020

Одним из решений для получения "фасетного" графа с отдельными легендами будет создание трех отдельных графиков и их сборка с использованием grid.arrange из gridExtra пакета:

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)

enter image description here

0 голосов
/ 13 марта 2020

Вы также можете рассмотреть возможность использования пакета 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) 

Создано в 2020-03-12 пакетом Представить (v0.3.0)

...