使用ggplot仅在1 bar中更改因子顺序

时间:2017-06-12 14:46:49

标签: r ggplot2 bar-chart

我试图在ggplot 2中仅在1 bar中反转因子顺序。重新排序数据而不将它们定义为因素通常有效,但不是最新版本。

实施例: 我想反转最后一列中的因子(绿色向上,红色向下)。

Example

library(ggplot2)

dados <- expand.grid(a = letters[1:5], b = letters[1:2])
dados$a <- paste(dados$a)
dados$b <- paste(dados$b)
dados$val <- rnorm(10, 5, 1)
ggplot(aes(x = a, y = val, fill = b), data = dados) + geom_bar(stat = 'identity')

dados2 <- rbind(tail(dados, -1), head(dados, 1))
ggplot(aes(x = a, y = val, fill = b), data = dados2) + geom_bar(stat = 'identity') # Used to work :/

1 个答案:

答案 0 :(得分:3)

我已在e中为column b分配了两个额外参数,请参阅下面的cd

    a b    val
2  b a 4.504735
3  c a 5.396658
4  d a 6.796288
5  e c 5.900308
6  a b 3.900510
7  b b 4.454316
8  c b 5.411198
9  d b 6.389902
10 e d 4.458425
1  a a 4.986175

by scale_fill_manual我颠倒了两种颜色

ggplot(aes(x = a, y = val, fill = b), data = dados2) + 
  geom_bar(stat = 'identity') +
  scale_fill_manual(values = c("a"= "red", "b"= "green",'c'= "green", "d"="red"))