r - 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
解决方案
获得具有单独图例的“方面”图的一种解决方案是创建三个单独的图并使用grid.arrange
from gridExtra
package 组装它们:
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)
推荐阅读
- python - 当我运行 Flask 应用程序时,我得到 Webhook Method Not Allowed on Browser
- postgresql - 无法在 Nix-Shell 中设置 Postgres
- android - 深度睡眠和唤醒在 Android 中的工作原理是什么?
- elasticsearch - 如何在stored_fields中获取嵌套字段?
- javascript - 使用@react-three/drei 时使用GLTF 崩溃场景
- javascript - Node.js/express - 服务器无法从客户端获取我的身体
- xamarin.forms - 在 Xamarin Forms 中实现底部工作表时未显示最后一个 ListView 项目
- javascript - 为什么 Enzyme 在我的 Jest 测试中找不到选择器?
- azure - 适用于 Dynamics365 的 Azure 服务标签
- python - 如何创建不评估的 if 语句?