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

时间:2021-04-23 02:58:01

标签: r ggplot2 stacked-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()

我目前的结果是:.

当前堆叠条形

enter image description here

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

期望输出

enter image description here

我已经阅读了多个答案,但是似乎没有任何效果。我认为我的数据表格式可能是问题的一部分,但是,我尝试了各种方法。感谢您提供任何指导。

1 个答案:

答案 0 :(得分:2)

您可以根据 '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() 

enter image description here