【发布时间】:2014-07-19 12:46:39
【问题描述】:
我正试图弄清楚如何转换我的条形图。现在,Gears 填充是按数字顺序排列的。我正在尝试能够手动设置Gears的顺序填写任意顺序。
我发现的所有其他示例都告诉我如何根据数据的计数或值以降序或升序对它们进行排序。我正在尝试以任意顺序手动设置顺序。因此,我想手动告诉它我希望数据显示为 3-5-4 或 5-3-4,而不是 3-4-5。
这是我现在拥有的:
library(data.table)
library(scales)
library(ggplot2)
mtcars <- data.table(mtcars)
mtcars$Cylinders <- as.factor(mtcars$cyl)
mtcars$Gears <- as.factor(mtcars$gear)
setkey(mtcars, Cylinders, Gears)
mtcars <- mtcars[CJ(unique(Cylinders), unique(Gears)), .N, allow.cartesian = TRUE]
ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) +
geom_bar(position="dodge", stat="identity") +
ylab("Count") + theme(legend.position="top") +
scale_x_discrete(drop = FALSE)
如果有任何不涉及ggplot2 的数据操作,我想使用data.table 来完成。感谢您的帮助!
【问题讨论】: