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)
I want each panel to have its own legend since the legend range is different
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
One solution to get a "facet" graph with individual legends will be to create three separate graphs and assemble them using 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)
You can also consider using the tmap
package. Here is a possible solution:
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)
Created on 2020-03-12 by the reprex package (v0.3.0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.