在ggplot2中设置堆叠条形图的条形顺序

时间:2020-06-15 07:57:35

标签: r ggplot2

给出如下数据示例:

  city     a     b
0   bj  4130  5505
1   sh  3869  4626
2   wh  3490  1511
3   sz  2566  1914
4   cd  1780  2315

我已使用以下代码绘制堆叠的条形图:

dfm <- melt(df[,c('city', 'a', 'b')], id.vars = 1)
dfm
ggplot(dfm, aes(x = city, y = value)) + 
  geom_bar(aes(fill = variable), stat = 'identity', position = 'stack') +
  geom_text(aes(x = city, y = value, label = value),
                  position = position_stack(vjust = .5), size = 2.5)

出: enter image description here

现在,我想基于ab的总和设置条形的降序,我该怎么做?在这种情况下,应为bj, sh, wh, sz, cd

谢谢。

2 个答案:

答案 0 :(得分:1)

在融化之前对city重新排序:

df <- structure(list(city = c("bj", "sh", "wh", "sz", "cd"), a = c(4130L, 
                                                                   3869L, 3490L, 2566L, 1780L), b = c(5505L, 4626L, 1511L, 1914L, 
                                                                                                      2315L)), row.names = c(NA, -5L), class = "data.frame")

library(reshape2)
library(ggplot2)

df$city <- reorder(df$city, -(df$a + df$b))

dfm <- melt(df[,c('city', "a", "b")], id.vars = 1)

ggplot(dfm, aes(x = city, y = value)) + 
  geom_bar(aes(fill = variable), stat = "identity", position = 'stack') +
  geom_text(aes(x = city, y = value, label = value),
            position = position_stack(vjust = .5), size = 2.5)

reprex package(v0.3.0)于2020-06-15创建

答案 1 :(得分:1)

您可以将x轴更改为分解因数,并按级别定义顺序。

ggplot(dfm, aes(x = factor(city, levels = c('bj', 'sh', 'wh', 'sz', 'cd')), y = value)) + 
  geom_bar(aes(fill = variable), stat = 'identity', position = 'stack') +
  geom_text(aes(x = city, y = value, label = value),
            position = position_stack(vjust = .5), size = 2.5)
相关问题