Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot Sort Percent Stacked Bar Chart

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.

like image 679
BBWesley Avatar asked Nov 15 '25 19:11

BBWesley


1 Answers

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

like image 101
Ronak Shah Avatar answered Nov 18 '25 12:11

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!