Reverse stop bar

I create a complex histogram using ggplot as follows:

plot_df <- df[!is.na(df$levels), ] ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = "fill") 

Which gives me something like this:

enter image description here

How can I change the order of the stacked bars themselves, so that level 1 is at the bottom and level 5 is at the top of each column?

I saw several questions on this issue (for example, “ How to control the ordering of a stacked histogram using an identifier on ggplot2” ), and the general solution seems to be to reorder the data at this level, since the one that ggplot uses determines the order

So I tried reordering with dplyr:

plot_df <- df[!is.na(df$levels), ] %>% arrange(desc(levels))

However, the plot goes the same way. It also doesn't seem to matter if I sort in ascending or descending order.

Here is a reproducible example:

 group <- c(1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4) levels <- c("1","1","1","1","2","2","2","2","3","3","3","3","4","4","4","4","5","5","5","5","1","1","1","1") plot_df <- data.frame(group, levels) ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = "fill") 
+12
source share
1 answer

The ggplot2 version 2.2.0 release ggplot2 on the Stacking panel suggest:

If you want to stack in reverse, try forcats::fct_rev()

 library(ggplot2) # version 2.2.1 used plot_df <- data.frame(group = rep(1:4, 6), levels = factor(c(rep(1:5, each = 4), rep(1, 4)))) ggplot(plot_df, aes(group, fill = forcats::fct_rev(levels))) + geom_bar(position = "fill") 

Reverse levels

This is the original plot :

 ggplot(plot_df, aes(group, fill = levels)) + geom_bar(position = "fill") 

Source story

Or using position_fill(reverse = TRUE) , as suggested by alistaire in his comment :

 ggplot(plot_df, aes(group, fill = levels)) + geom_bar(position = position_fill(reverse = TRUE)) 

enter image description here

Note that the levels (colors) in the legend are not in the same order as in the stacked bars.

+31
source

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


All Articles