I'm using ggplot()
and geom_sf()
to plot a faceted map (s. below code) and color units along a scale_fill_gradient()
by a variable (value
in the example below), before faceting by another variable (group
). This works; but now I would like to change the color at the gradient's higher end (not midpoint or lower) depending on the facet. Based on this answer, I have saved this in a separate column (color_high
) in the plotting data frame. However, I cannot get it to translate into the plotting scale.
Can someone point me to the right direction? Below is the working code with a single fill gradient. The expected output has high values as defined in color_high
(red in Group A, green in Group B).
library(sf)
library(tidyverse)
theme_set(theme_bw())
library(giscoR)
ger_fedstates <- gisco_get_nuts(nuts_level = 1, resolution = 10, country = "Germany", year = 2021)
dat <- read.table(text = "state value group
Sachsen 10 a
Sachsen 1 b
Bayern 3 a
Bayern 30 b
Rheinland-Pfalz 50 a
Rheinland-Pfalz 50 b
Saarland 70 a
Saarland 70 b
Schleswig-Holstein 9 a
Schleswig-Holstein 90 b
Niedersachsen 100 a
Niedersachsen 100 b
Nordrhein-Westfalen 80 a
Nordrhein-Westfalen 80 b
Baden-Württemberg 60 a
Baden-Württemberg 60 b
Brandenburg 40 a
Brandenburg 40 b
Mecklenburg-Vorpommern 20 a
Mecklenburg-Vorpommern 20 b
Bremen 40 a
Bremen 40 b
Hamburg 60 a
Hamburg 60 b
Hessen 15 a
Hessen 15 b
Berlin 10 a
Berlin 10 b
Thüringen 80 a
Thüringen 80 b
Sachsen-Anhalt 20 a
Sachsen-Anhalt 20 b", header = T) %>%
mutate(color_high = case_when(group=="a"~"red", group=="b"~"green"))
plot_df <- full_join(ger_fedstates, dat, by=c("NUTS_NAME" = "state"))
plot_df %>%
ggplot() +
geom_sf(aes(fill = value)) +
theme(axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.line.x = element_blank(),
axis.line.y = element_blank(),
legend.position = "right",
legend.title.align = 0) +
scale_fill_gradient2(low = "grey40",
mid = "white",
high = "#0000ff", # this should be the value of "color_high" column
midpoint=50,
guide = "colourbar",
aesthetics = "fill") +
facet_wrap(~group, labeller = labeller(group=c(a="Group A", b="Group B", c="Group C")))