Eric
Eric

Reputation: 65

Reorder Factor Levels By Another Factor

I'm trying to create a bar graph using ggplot2, where the bars are ordered by the proportion of observations in a certain level of a filled factor. For example, suppose I have data like the following:

my_data <- data.frame(group = as.factor(rep(1:3, each = 5)), success = as.factor(c('yes','yes','yes','yes','no','yes','yes','no','no','no','yes','no','no','no','no')))

   group success
1      1     yes
2      1     yes
3      1     yes
4      1     yes
5      1      no
6      2     yes
7      2     yes
8      2      no
9      2      no
10     2      no
11     3     yes
12     3      no
13     3      no
14     3      no
15     3      no

I want to plot each group on the x-axis, filled by the proportion of observations for each success level.

ggplot(my_data, aes(x = group, fill = success)) +
  geom_bar(position = 'fill')

Is there any way to reorder my groups, so that they are shown in ascending (or descending) order of proportion of successes?

Upvotes: 2

Views: 685

Answers (2)

Waldi
Waldi

Reputation: 41260

Use fct_reorder from forcats package:

ggplot(my_data, aes(x = forcats::fct_reorder(group,success == 'yes',mean,.desc = T), fill = success)) +
  geom_bar(position = 'fill')+
  xlab("group")

what it does is to reorder group according to mean of success=='yes' which gives the success rate.

You can invert the order with the .desc argument.

Upvotes: 5

akrun
akrun

Reputation: 887831

We could get the proportion after grouping by 'group'

library(dplyr)
library(ggplot2)
my_data %>% 
  group_by(group) %>% 
  mutate(prop = mean(success == 'yes')) %>%
  ungroup %>%
  ggplot(aes(x = reorder(group, prop), fill = success)) + 
       geom_bar(position = 'fill') +
       xlab('group')

Upvotes: 2

Related Questions