R ggplot 排序百分比堆叠条形图

R ggplot Sort Percent Stacked Bar Chart

我正在尝试根据“良好”百分比对 ggplot 进行排序。下面是我正在使用的数据框。还有我现在得到的以及我理想中想要拥有的。

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

我目前的成绩是:.

当前堆积条

理想情况下,我的结果应该是这样的:

期望的输出

我已经阅读了多个答案,但是似乎没有任何效果。我假设我的数据 table 格式可能是问题的一部分,但是,我尝试了各种方法。任何指导表示赞赏。

您可以过滤数据 'Good' 条件,根据它的降序分配因子水平,然后绘制数据。

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