Home > database >  Barplot with fill and pattern by group (GGPattern)
Barplot with fill and pattern by group (GGPattern)

Time:04-26

I have been trying to create a custom bar plot where I can change the color and pattern (stripes or no stripes) per group.

structure(list(Level= c(0.2, 0.3, 0.25, 0.35, 0.4, 0.5, 0.5, 0.6, 0.15, 0.35), Group= c("A", "A", 
"B", "B", "C", "C", "D", "D", 
"E", "E"), Condition = c("no", "yes", "no", "yes", "no", "yes", "no", 
"yes", "no", "yes")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

I have tried the following which creates the graph below. Example

I would however like to have both groups in white color, and if the bars where the condition == yes have black stripes in them as often seen in ggpattern plots.

Using ggpattern I could not find a feasible solution [Error in seq.default(from, to, by) : invalid '(to - from)/by'] was one of my most encountered errors.

p<- ggplot(z, aes(fill=Condition, y=Level, x=Group, pattern = Condition))  
  geom_bar(position="dodge", stat="identity")  
  ggpubr::theme_pubr()  
  theme(legend.position = "top")  
  theme( panel.background = element_rect(colour = "black", size=0.5))  
  labs(x = "Group", y = "Level") 
  scale_y_continuous(breaks=seq(0, 0.8, 0.1)) 
  scale_fill_discrete(name = "", labels = c("No", "Yes")) 

CodePudding user response:

Are you looking for something like this?

ggplot(z, aes(fill=Condition, y=Level, x=Group, pattern = Condition, 
              pattern_type = Condition))  
  geom_bar_pattern(position="dodge", stat="identity", pattern_fill = "black",
                   fill = "white", colour = "black", pattern_spacing = 0.01,
                   pattern_frequency = 5, pattern_angle = 45)  
  ggpubr::theme_pubr()  
  theme(legend.position = "top")  
  theme( panel.background = element_rect(colour = "black", size=0.5))  
  labs(x = "Group", y = "Level") 
  scale_y_continuous(breaks=seq(0, 0.8, 0.1), limits = c(0, 0.8))  
  scale_pattern_manual(values=c('stripe', 'none'))  
  scale_pattern_type_manual(values=c(NA, NA))

enter image description here

  • Related