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

Ideally, my result would be like this:
Desired Output

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.
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()

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