ggplot2堆积条不按手动定义的因子顺序排序

时间:2014-08-26 18:22:32

标签: r ggplot2

我想手动定义每个堆叠条中项目的顺序。从我所做的所有研究中,我应该能够通过在绘图之前手动定义这些因素的顺序来做到这一点。出于某种原因,我没有成功。

以下是原始数据:

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

产生以下情节:

enter image description here

我将'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

产地:

enter image description here

1 个答案:

答案 0 :(得分:2)

以下为我效劳:

df$variable <- relevel(df$variable, "i")

library(ggplot2)
p <- ggplot() + 
  geom_bar(data=df,aes(x=cross_valid,y=value,fill=variable,order=variable),stat='identity') +
  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('h','g','f','e','d','c','b','a','i'),
                    labels=c('h','g','f','e','d','c','b','a','i'))
p

我使用relevel更改了因子级别顺序,并向order添加了aes参数。 修改:更改breakslabels的顺序也会相应地调整图例。

enter image description here

第二次编辑:对不起,解决方案已在上面的评论中发布,在回答之前没有看到...