我在想怎么转换我的条形图。现在,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来完成。谢谢你的帮助!
发布于 2014-05-30 05:26:18
您需要正确设置因子级别。
假设你有一个因素
> x=factor(c("a","c","b"))
> x
[1] a c b
Levels: a b c顺序为a c b,但绘图顺序为a b c,因为默认因子以字母数字顺序生成高程。
也许您希望绘图顺序与矢量中的顺序相匹配-我们可以指定因子级别应遵循每个级别首次遇到的顺序:
> z=factor(x,unique(x))
> z
[1] a c b
Levels: a c b也许这两个都不是我们想要的-例如,我们可能想要c a b。
我们可以手动设置顺序
> y=factor(c("a","c","b"),levels=c("c","a","b"))
> y
[1] a c b
Levels: c a b或者我们可以稍后通过显式指定每个级别的位置来调整因子:
> reorder(y,x,function(x)c(a=2,b=3,c=1)[x])
[1] a c b
attr(,"scores")
c a b
1 2 3
Levels: c a b现在您知道了这一点,您可以应用您在其他地方找到的技术,例如
https://stackoverflow.com/questions/23943057
复制相似问题