0

I would like to change the order of the bars to Before-After.

I looked at other similar posts eg: ggplot bar plot with facet-dependent order of categories but couldn't figure out how to apply those to this.

df<-data.frame(
  When<-c('Before', 'Before','After','After'),
  Group<-c('Untreated','Treated','Untreated','Treated'),
  Mean<-c(3,4,3,5)
)

ggplot(df, aes(x = Group, y = Mean, fill = When))+
  geom_bar(stat='identity', position=dodge) +
  scale_x_discrete(limits = rev(levels(df$Group)))

enter image description here

Community
  • 1
  • 1
SunWuKung
  • 527
  • 4
  • 16

1 Answers1

1
ggplot(df, aes(x = Group, y = Mean, fill = factor(When, levels = c("Before", "After")))) +
   geom_bar(stat='identity', position="dodge") +
   scale_x_discrete(limits = rev(levels(df$Group))) +
   guides(fill = guide_legend(title = "When"))
Codutie
  • 1,055
  • 13
  • 25