Home > Software design >  ggplot: grouped bar plot - alpha value & legend per group
ggplot: grouped bar plot - alpha value & legend per group

Time:03-10

I have data with two data points for an observation (indicated by the unique pty/time combination in res), which I would like to plot as barplot.

Consider this toy data:

df <- data.frame(pty = c("A","A","B","B","C","C"),
       print_col = c("#FFFF00", "#FFFF00", "#000000", "#000000", "#ED1B34", "#ED1B34"),
       time = c(2020,2016,2020,2016,2020,2016),
       res = c(20,35,30,35,40,45))

I am using ggplot(df) geom_bar(aes(pty, res , fill = as.factor(pty), group=as.factor(time)), position = "dodge", stat = "summary" , fun = "mean") to plot this with the following result (s. below).

bar plot

However, I would like to alter two things:

  1. coloring: (i) the bar colors should be taken from the column print_col for the respective row and (ii) for time==2016, I want an alpha value of .5 for better readability.
  2. legend: the fill legend is unnecessary. Instead, I want the legend for group (i.e. "Time" as title and "2020" / "2016" as entries).

I couldn't figure out a way to achieve these - can someone point me into the right direction?

CodePudding user response:

Adding an alpha is as simple as mapping a column to the alpha aesthetic, which gives you a legend by default. Using fill = I(print_col) automatically sets an 'identity' fill scale, which hides the legend by default.

library(ggplot2)

df <- data.frame(pty = c("A","A","B","B","C","C"),
                 print_col = c("#FFFF00", "#FFFF00", "#000000", "#000000", "#ED1B34", "#ED1B34"),
                 time = c(2020,2016,2020,2016,2020,2016),
                 res = c(20,35,30,35,40,45))


ggplot(df)  
  geom_bar(aes(pty, res, fill = I(print_col), group = time,
               alpha = as.factor(time)),
           position = "dodge", stat = "summary", fun = "mean")  
  # You can tweak the alpha values with a scale
  scale_alpha_manual(values = c(0.3, 0.7))

Created on 2022-03-09 by the enter image description here

  • Related