invictus
invictus

Reputation: 1971

reorder stacked bar chart with two levels ggplot2

I have this data:

# A tibble: 6 x 3
  question category percent
  <chr>    <chr>      <dbl>
1 No       A           0.82
2 No       C           0.8 
3 No       B           0.77
4 Yes      B           0.23
5 Yes      C           0.2 
6 Yes      A           0.18

and I make a stacked bar chart:

data %>% 
  ggplot(aes(x = category, y = percent, fill = question)) + 
  geom_col(position = "fill") + 
  coord_flip()

but what I really want is to arrange the bars descending in "Yes". That means Category "B" should be top, "C" in the middle", and "A" at the bottom.

If I didn't have a stacked chart I could do this with reorder(). But how can I do this with a stacked chart?

The data:

structure(list(question = c("No", "No", "No", "Yes", "Yes", "Yes"
), category = c("A", "C", "B", "B", "C", "A"), percent = c(0.82, 
0.8, 0.77, 0.23, 0.2, 0.18)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

enter image description here

Upvotes: 0

Views: 470

Answers (2)

Koundy
Koundy

Reputation: 5503

You can manually reorder the category variable by making in an ordered factor.

dat$category <- factor(dat$category, levels = c('B', 'C', 'A'), ordered = T)

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388817

arrange the data, set the factors and plot.

library(dplyr)
library(ggplot2)

data %>% 
  arrange(desc(question), percent) %>%
  mutate(category = factor(category, unique(category))) %>%
  ggplot(aes(x = category, y = percent, fill = question)) + 
  geom_col(position = "fill") + 
  coord_flip()

enter image description here

Upvotes: 2

Related Questions