【问题标题】:Creating a grouped bar plot in R with bars unarranged在 R 中创建一个分组条形图,其中条形未排列
【发布时间】:2021-06-03 11:41:00
【问题描述】:

我想创建一个分组条形图。我意识到这些条是根据图例中项目的字母顺序排列的。如何在不按字母顺序重新排列条形的情况下使代码生成图形?

library(ggplot2)

# creating dataset
Year <- c(rep("2012" , 3) , rep("2013" , 3) , rep("2014" , 3) , rep("2015" , 3) )
Legend <- rep(c("A" , "X" , "E") , 4)
Count <- abs(rnorm(12 , 0 , 15))
data <- data.frame(Year,Legend,Count)

# Grouped barplt
ggplot(data, aes(fill=Legend, y=Count, x=Year)) + 
  geom_bar(position="dodge", stat="identity")

如图所示,条形按 A、E、X 的顺序排列 - 但我希望它按表中的顺序排列(A、X、E)。

我希望在这个问题上得到一些帮助。谢谢。

【问题讨论】:

  • 尝试转换为因子并按所需顺序设置级别:factor(Legend, levels = c("A", "X", "E"))
  • 非常感谢@stefan 的建议。我试过+ scale_fill_discrete(limits = c("A", "X", "E")),但只有传说受到影响。条形图仍按字母顺序排列。
  • 对不起。我的错。然后尝试因子方法。

标签: r ggplot2 plot bar-chart


【解决方案1】:

下面是一个适用于您的代码的 sn-p。它使用dplyr::mutate()Legend 列更改为因子。

library(ggplot2)
library(dplyr)

data %>%
  mutate(Legend = factor(Legend, levels = c("A", "X", "E"))) %>%
  ggplot(aes(fill = Legend, y = Count, x = Year)) +
    geom_bar(position = "dodge", stat = "identity")

【讨论】:

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