ggplot2: nested colors?

Greetings all,

I'm trying to produce a plot like the one below:

library(tidyverse)

# Create dummy data:
foo <- tibble( 
  Group = rep(c("Treatment A", "Treatment B", "Control"), each = 2),
  Time = factor(rep(c(0, 1), times = 3), labels = c("pre", "post")),
  Score = c(0.52, 0.63, 0.49, 0.76, 0.51, 0.49),
  my_colors = factor(1:6, labels = paste0(Group, c("pre", "post")))
)

# Plot dummy data:
foo %>% ggplot(aes(x = Time, y = Score, fill = my_colors)) +
  geom_bar(stat = "identity") +
  facet_wrap(~ Group) +
  scale_fill_brewer(palette = "Paired")

ggplot2_nested_colors !

It's pretty intuitive what's going on, visually: each group is assigned a general color category, and the "levels" of each group is assigned a shade of that color.

The problem is I can't find a way of making the legend fit this simple pattern. In my mind at least it should be as simple as something like this:

foo %>% ggplot(
  aes(
    x = Time,
    y = Score,
    fill = c("Group", "Time") # This will yield an error
  )
) # + geom_... (and so on)

Do you know of any method or package that can help me achieve this? Thanks for taking the time.

Edit: What I would like to see is a separate legend for each group. Taking the above plot as an example, one legend header would read "Treatment A" and below it would be two blue color swatches, each labelled "pre" and "post"; below that would be another legend header reading "Treatment B" with its color swatches and labels below, etc.

Are you thinking of something this way.

library(tidyverse)
library(ggpubr)

# Create dummy data:
foo <- tibble( 
  Group = rep(c("Treatment A", "Treatment B", "Control"), each = 2),
  Time = factor(rep(c(0, 1), times = 3), labels = c("pre", "post")),
  Score = c(0.52, 0.63, 0.49, 0.76, 0.51, 0.49),
  my_colors = factor(1:6, labels = paste0(Group, c("pre", "post"))),
)

group <- unique(foo$Group)
plotlist<- list()
color<-  c("Blues", "Greens", "Oranges")
names(color)<- group
for (i in group){
# Plot dummy data:
  
p<- foo %>% filter(Group == i) %>% ggplot(aes(x = Time, y = Score, fill = Time)) +
  geom_bar(stat = "identity") +
  scale_fill_brewer(palette = color[[i]], )+labs(fill=i)
  x= 1
plotlist[[i]] = p
  
  }

plot<- print(ggarrange(plotlist = plotlist, ncol=3, legend = "bottom"))

[image]

Created on 2021-03-25 by the reprex package (v1.0.0)
image

Yes, thank you.

I see what you've done with the loop, interesting solution. The color loop is a nice touch.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.