我想要创建一个分组条形图。我意识到这些条子是根据传说中物品的字母顺序排列的。如何使代码生成图形而不按字母顺序重新排列条形?
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)。
我希望在这个问题上得到一些帮助。谢谢。
发布于 2021-06-03 13:56:12
下面是一个应该适用于您的代码的代码段。它使用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")https://stackoverflow.com/questions/67820814
复制相似问题