【发布时间】:2014-08-26 18:22:31
【问题描述】:
我想手动定义每个堆叠条中项目的顺序。从我所做的所有研究中,我应该能够通过在绘图之前手动定义这些因素的顺序来做到这一点。由于某种原因,我没有成功。
这是原始数据:
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=会覆盖因子的默认顺序。 -
@MrFlick 取消休息=似乎没有帮助。见编辑 1。
-
两件事:(1)你不需要
unique或ordered在你的因子调用中,但你确实需要列出所有原始级别;因为你正在介绍 NA,(2)尝试aes(...,order = variable)。 -
@joran,
order=variable,成功了。 -
@AlK 方便地记录在
?aes_group_order的最底部。 ;) 谁不会在那里找到它...?