【问题标题】:How to reorder the groups in a grouped bar-chart [duplicate]如何重新排序分组条形图中的组[重复]
【发布时间】:2017-11-27 06:08:37
【问题描述】:

我想创建一个分组条形图,其中组以特定顺序出现。这是一个详细的例子。

df <- data.frame(Groups = c("B","B","B","C","C","A","A","A","A","A"), 
                 Ages = c(3,4,4,5,3,4,5,3,3,5))

df_cast <- dcast(data = df, formula = Groups ~ Ages)    
df_bars <- melt(data = df_cast, id.vars = 'Groups')

ggplot(data = df_bars, aes( x = Groups, y = value, fill = variable ) ) + 
    geom_bar( stat = 'identity', position = 'dodge' ) + 
    labs(title="Groups ages", x = "Groups", y = "Frecuency") + 
    labs(fill = "Ages") + theme(plot.title = element_text(hjust = 0.5))

这些组是 B、C 和 A,我希望它们按顺序出现在条形图中,上面的命令按字母顺序排列它们。

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    我们需要将“组”转换为factor,并按该顺序指定levels

    df_bars$Groups <- factor(df_bars$Groups, levels = c('B', 'C', 'A'))
    

    然后在 OP 的帖子中使用 ggplot 代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多