4

I am attempting to sort a ggplot based on the "good" Percentage. Below is a data frame that I am working with. Also What I am getting now and what I would like to have ideally.

library(ggplot2)

a <- c("Nevada", "Maine", "North Carolina", "South Carolina", "Texas", "Rhode Island", 
       "Nevada", "Maine", "North Carolina", "South Carolina", "Texas", "Rhode Island")
b <- c(0.81, 0.72, 0.65, 0.55, 0.45, 0.35, 0.19, 0.28, 0.35, 0.45, 0.55, 0.65)
d <- c("Good", "Good", "Good", "Good", "Good", "Good", "Bad", "Bad", "Bad", "Bad", "Bad", "Bad")

df <- data.frame(a,b,d)
names(df) <- c("State", "Percentage", "Condition")
 
ggplot(df, aes(x=State, y=Percentage, fill=Condition))+
  geom_bar (position = "fill", stat="identity")+
  coord_flip()

My current result is:.

Current Stacked Bar

enter image description here

Ideally, my result would be like this:

Desired Output

enter image description here

I have read multiple answers, however, nothing seems to work. I assume my data table format could be part of the problem, however, I have tried various approaches. Any guidance is appreciated.

NicolasH2
  • 774
  • 5
  • 20
BBWesley
  • 43
  • 3
  • can you specify why the output you have is not what you want? Do you want the vizualization to be like in your ideal example or the order on the y axis? – NicolasH2 Apr 23 '21 at 08:07

1 Answers1

5

You can filter the data for 'Good' condition assign the factor levels based on the decreasing order of it and then plot the data.

library(dplyr)
library(ggplot2)

df %>%
  filter(Condition == 'Good') %>%
  arrange(desc(Percentage)) %>%
  bind_rows(df %>% filter(Condition != 'Good')) %>%
  mutate(State = factor(State, unique(State)), 
         Percentage = Percentage * 100, 
         label = paste0(Percentage, '%')) %>%
  ggplot(aes(x=State, y=Percentage, fill = Condition, label = label))+
  geom_col() +
  geom_text(size = 3, position = position_stack(vjust = 0.5)) + 
  coord_flip() 

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • This did not work for me, maybe because I had three levels. However, fct_reorder2 did the trick. https://forcats.tidyverse.org/reference/fct_reorder.html – meier_flo May 03 '23 at 06:27