ah bon
ah bon

Reputation: 10021

Set order of bars for stacked barcharts in ggplot2

Given a data example like this:

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

I have used the following code to plot a stacked barchart:

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)

Out: enter image description here

Now I would like to set a decreasing order of bars based on sum of a and b, how could I do that? At this case, it should be bj, sh, wh, sz, cd.

Thanks.

Upvotes: 2

Views: 107

Answers (2)

MarBlo
MarBlo

Reputation: 4524

you can change the x-axis to factor and defined the order by the levels.

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)

Upvotes: 1

stefan
stefan

Reputation: 124183

Reorder city before melting:

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)

Created on 2020-06-15 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions