我希望能够手动定义每个堆叠条中项目的顺序。根据我所做的所有研究,我应该能够在绘图之前手动定义这些因素的顺序。但由于某种原因,我没有成功。
以下是原始数据:
现在绘制图表:
以下是原始数据:
df <- structure(list(cross_valid = structure(c(1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("1",
"2"), class = "factor"), variable = structure(c(1L, 1L, 2L, 2L,
3L, 3L, 4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L), .Label = c("a",
"b", "c", "d", "e", "f", "g", "h", "i"), class = "factor"), value = c(0,
0, 0, 0, 3.546, 0, 0, 0, 28.0927688833, 4.689, 0.4887, 1.134,
20.886690705, 16.8620595883, 14.8086, 18.648, 20.5713, 44.046
)), row.names = c(NA, -18L), class = "data.frame", .Names = c("cross_valid",
"variable", "value"))
看起来像:
> head (df)
cross_valid variable value
1 1 a 0.000
2 2 a 0.000
3 1 b 0.000
4 2 b 0.000
5 1 c 3.546
6 2 c 0.000
df$variable
的当前顺序和级别:
> df$variable
[1] a a b b c c d d e e f f g g h h i i
Levels: a b c d e f g h i
现在我改变了df$variable
的顺序:
df$variable <- factor(df$variable, levels = unique(c("i","a","b","e","g","f","h")),ordered=TRUE)
现在绘制图表:
library(ggplot2)
p <- ggplot() + geom_bar(data=df,aes(x=cross_valid,y=value,fill=variable),stat='identity')
p <- p + scale_fill_manual("",values=c('a'='darkred','b'='blue','c'='black','d'='darkolivegreen1','e'='green','f'='darkorchid','g'='yellow',
'h'='snow4','i'='darkgray'),
breaks=c('i','h','g','f','e','d','c','b','a'),
labels=c('i','h','g','f','e','d','c','b','a'))
p
这将产生以下图表:
我定义 'i' 和 'h' 在条形上的两端,但它们仍然相邻。 有没有关于为什么会发生这种情况的想法?也许我的数据有些奇怪?
谢谢
-al
编辑1:
根据 @MrFlick 的建议,我去掉了换行符,但仍然发现 'i' 和 'h' 相邻,即使级别已将它们定义为在条形的两端。
> df$variable
[1] a a b b c c d d e e f f g g h h i i
Levels: i < a < b < c < d < e < g < f < h
修改后的图表代码:
p <- ggplot() + geom_bar(data=df,aes(x=cross_valid,y=value,fill=variable),stat='identity')
p <- p + scale_fill_manual("",values=c('a'='darkred','b'='blue','c'='black','d'='darkolivegreen1','e'='green','f'='darkorchid','g'='yellow',
'h'='snow4','i'='darkgray'))
p
生成:
scale_fill_manual
使用了breaks=
,覆盖了因子的默认顺序。 - MrFlickunique
或ordered
,但是你需要列出所有原始的水平;否则会引入NA值。(2)尝试使用aes(..., order = variable)
。 - joranorder=variable
,解决了问题。 - cherrytree?aes_group_order
的底部。;)谁会不在那里找到它...?<讽刺> - joran