Home > Software design >  Standard column width in facetted and grouped ggplot bar plot
Standard column width in facetted and grouped ggplot bar plot

Time:02-25

I've made a bar chart using ggplot with grouped data, and facetted with facet_grid. The column widths are inconsistent, so I want to make them all the same. I've enter image description here

But when I try to standardise the column widths with preserve="single", it gets messed up:

ggplot(data, aes(x=label2, y=conc, colour=mda_label, fill=mda_label))  
  facet_grid(. ~ grp2, scales="free_x", space="free")  
  stat_summary(fun = mean, geom = "bar", position = position_dodge(preserve="single"))   
  stat_summary(fun.data = mean_se, geom = "errorbar", colour="black", width=0.5,
               position = position_dodge(width=0.9, preserve="single"))  
  geom_point(position = position_dodge(width=0.9, preserve="single"), pch=21, colour="black")  
  scale_y_continuous(trans='pseudo_log',
                     labels = scales::number_format(accuracy=0.01))  
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

enter image description here

CodePudding user response:

Since you're using data that as 0 values, you could make the 0 values for the other 'mda_label' on grp2/label2 standard categories.

data <- rbind(data, data.frame(grp2 = c("standard", "standard"),
                           label2 = c("standard", "standard"),
                           mda_label = c("mda_20", "mda_200"),
                           conc = c(0, 0)))

Also you never actually make the bar plot

data %>%
  ggplot(aes(label2, conc, fill = mda_label))  
  geom_col(position = position_dodge(width = 1))  
  facet_grid(. ~ grp2, scales = "free", space = "free")
  • Related