在 R 中创建一个分组的条形图,条形图未排列

Creating a grouped bar plot in R with bars unarranged

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

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 的顺序排列 - 但我希望按 table(A、X、E)中的顺序排列。

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

下面是一段适用于您的代码的代码段。它使用 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")