I am trying to assign groups of facet panels individual color schemes using ggplot 2. In the below example my goal is that A and B would have the same pallet, C would have a different pallet, and D and E would have the same pallet.
# Number of IDs
n_ids <- 10
# Generate IDs
ids <- paste0("ID_", 1:n_ids)
# Number of periods per ID
n_periods <- 3
# Generate periods
periods <- rep(c("P1", "P2", "P3"), each = n_ids)
# Number of categories
n_cats <- 5
# Generate categories
categories <- rep(LETTERS[1:n_cats], times = n_ids * n_periods)
# Generate values
values <- rnorm(n_ids * n_periods * n_cats, 100, 15)
# Assemble into dataframe
df <- data.frame(ID = ids,
Period = periods,
Category = categories,
Value = values)
# Plot
p <- ggplot(df, aes(x=Period, y=Value, fill=Period)) +
geom_boxplot() +
geom_jitter(width=0.2,alpha=0.4, size=1) +
facet_wrap(~Category, ncol=6, scales='free') +
labs(title="Repetitive Behavior Score", x="Group", y="Value")
# Color vector
colors <- c("#1F78B4", "#E69F00", "#33A02C", "#FB9A99")
# Map colors to categories
color_map <- c(
"A" = "#1F78B4",
"B" = "#1F78B4",
"C" = "#E69F00",
"D" = "#33A02C",
"E" = "#33A02C"
)
# Set fill scale
p +
scale_fill_manual(values = color_map)
but they are all just returning gray… has anybody tried this before? I know it can be done with scale_fill and scale_color but I can’t find examples for facet panels.
>Solution :
You could map the fill aesthetic to the interaction of your x axis and faceting variables. The downside is that you need to specify colors manually.
ggplot(df, aes(Period, Value, fill = interaction(Period, Category))) +
geom_boxplot() +
geom_jitter(width = 0.2, alpha = 0.4, size = 1) +
facet_wrap(~Category, ncol = 6, scales = 'free') +
labs(title = "Repetitive Behavior Score", x = "Group", y =" Value") +
scale_fill_manual(values = c(rep(c("red4", "green4", "blue4"), 2),
c("hotpink", "orange", "dodgerblue"),
rep(c("purple3", "beige", "gray80"), 2)),
guide = guide_none()) +
jtools::theme_apa()
