【问题标题】:How to change the order of variables which was ordered by alphabetically in ggplot graph? [duplicate]如何更改在ggplot图中按字母顺序排列的变量的顺序? [复制]
【发布时间】:2020-11-19 16:30:52
【问题描述】:

当我有名为“汇总”的数据时,

如果我使用以下代码制作条形图

ggplot (data=summarized , aes(x=Stage, y=mean, fill=heat)) + 
  geom_bar(stat="identity",position="dodge", width = 0.5) + 
  geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.5) ,width=0.2) +
  scale_fill_manual(values= c ("darkslategray","azure3"), name="Treatment")

图表是这样的,但我希望 Pre-Anthesis 先出现。如何更改此顺序?

非常感谢,

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试这个:

    library(dplyr)
    library(ggplot2)
    #Code
    summarized %>%
      mutate(Stage=factor(Stage,levels = c('Pre-Anthesis','Post-Anthesis'),ordered = T)) %>%
      ggplot(aes(x=Stage, y=mean, fill=heat)) + 
      geom_bar(stat="identity",position="dodge", width = 0.5) + 
      geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.5) ,width=0.2) +
      scale_fill_manual(values= c ("darkslategray","azure3"), name="Treatment")
    

    你也可以直接在ggplot2函数scale_x_discrete()试试:

    #Code2
    ggplot (data=summarized , aes(x=Stage, y=mean, fill=heat)) + 
      geom_bar(stat="identity",position="dodge", width = 0.5) + 
      geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.5) ,width=0.2) +
      scale_fill_manual(values= c ("darkslategray","azure3"), name="Treatment")+
      scale_x_discrete(limits=c('Pre-Anthesis','Post-Anthesis'))
    

    输出(两种情况下):

    【讨论】:

    • 非常感谢,鸭子。你的代码完全有效!!!非常感谢!!!
    • 您还可以使用forcats 包中的fct_relevelState 变量中的因子水平进行重新排序。类似mutate(State = fct_relevel(State, c("Pre-Anthesis", "Post-Anthesis")
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 2020-03-29
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多