ggplot2, geom_bar, dodge, order of bars
Asked Answered
E

1

8

I'd like to have ordered bars in dodge geom_bar. Do you know how to deal with it?

My code:

ttt <- data.frame(typ=rep(c("main", "boks", "cuk"), 2),
                  klaster=rep(c("1", "2"), 3),
                  ile=c(5, 4, 6, 1, 8, 7))

ggplot()+
    geom_bar(data=ttt, aes(x=klaster, y=ile, fill=typ),
             stat="identity", color="black", position="dodge")

And example plots to better understand the problem:

What I have:

What I would like to have:

Execrable answered 14/10, 2015 at 13:44 Comment(1)
Hello Marta, welcome to StackOverflow!Corliss
M
14

One option would be to make a new variable to represent the order the bars should be within each group and and add this variable as the group argument in your plot.

Lots of ways to that task of making the variable, here's a way using function from dplyr. The new variable is based on ranking ile in descending order within each klaster group. If you have ties in any group you'll want to figure out what you want to do in that case (what order should the bars be in given ties?). You may want to set the ties.method argument in rank away from the default, probably to "first" or "random".

library(dplyr)
ttt = ttt %>% 
    group_by(klaster) %>% 
    mutate(position = rank(-ile))
ttt
Source: local data frame [6 x 5]
Groups: klaster [2]

     typ klaster   ile  rank position
  (fctr)  (fctr) (dbl) (dbl)    (dbl)
1   main       1     5     3        3
2   boks       2     4     2        2
3    cuk       1     6     2        2
4   main       2     1     3        3
5   boks       1     8     1        1
6    cuk       2     7     1        1

Now just add group = position into your plot code.

ggplot() +
    geom_bar(data=ttt, aes(x=klaster, y=ile, fill=typ, group = position),
                     stat="identity", color="black", position="dodge")

enter image description here

Mucus answered 14/10, 2015 at 23:12 Comment(2)
Generally it works - with one exception. When two bars have the same height. Like here: ttt <- data.frame(typ=rep(c("main", "boks", "cuk"), 2), klaster=rep(c("1", "2"), 3), ile=c(5, 4, 6, 7, 8, 7)). Do you know how to solve this situation?Execrable
@Execrable Depends on bit on what order the bars should be in given a tie, but given that answer can set the ties.method argument in rank away from the default "average" to one of the other options. See the rank help page for more info.Mucus

© 2022 - 2024 — McMap. All rights reserved.