2017-02-24 78 views
0

我想將條形的順序更改爲Before-After。ggplot的條形順序填充,stat =身份和位置=閃避

我看了其他類似的帖子,例如: ggplot bar plot with facet-dependent order of categories但無法弄清楚如何將這些應用於此。

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

回答

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"))