Ggplot2, geom_bar, dodge, order of bars

I would like to order bars at dodge geom_bar. Do you know how to deal with this? My code is:

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 sample graphs to better understand the problem:

What I have

What i would like to have

+4
source share
1 answer

One option is to make a new variable to represent the order in which the bars should be inside each group, and add this variable as an argument groupin your chart.

, dplyr. ile klaster. , , ( ?). ties.method rank , , "first" "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

group = position .

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

enter image description here

+5

Source: https://habr.com/ru/post/1611611/


All Articles