Customizing Bar Patterns with ggplot2: A Step-by-Step Guide

To modify your ggplot2 code to include patterns in the bars, we can use ggpattern::geom_bar_pattern instead of geom_bar. This will allow us to add a pattern aesthetic (aes(pattern = Time)) and then set a scale for that pattern using scale_pattern_discrete.

Here is how you can modify your code:

library(ggplot2)
library(ggpattern)

ggplot(example, aes(x=Type, y=value, fill=Time))+
  ggpattern::geom_bar_pattern(aes(pattern = Time), stat="identity", position="dodge", color="black",alpha = 1, width=0.8) +
  geom_errorbar(aes(ymax=value+sd, ymin=value-sd), position=position_dodge(0.8), width=0.25, color="black", alpha=0.5, show.legend = FALSE)+
  scale_fill_brewer(name="Time / min", palette = "Greens", guide = guide_legend(label.hjust = 0))+
  theme_bw(base_size = 20) +
  theme( panel.grid.major=element_blank(), panel.grid.minor=element_blank(),axis.text=element_text(size=20), axis.title=element_text(size=22,face="bold"), legend.title=element_text(size=14, face="bold"),legend.text=element_text(size=12), axis.text.x=element_text(angle = 45, hjust = 1),legend.position = c(0.94, 0.80) )+
  labs(y = "Value", x= "")+ 
  scale_y_continuous(expand = c(0, 0),limits=c(0, 25))+
  facet_grid(.~response,labeller = label_both) +
  ggpattern::scale_pattern_discrete(name="Time / min")

Note that I’ve removed the ggpubr and egg libraries as they’re not necessary for this task. Also, note that you can add more patterns by using different aesthetics in aes(pattern = ...).


Last modified on 2023-06-13