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

4

我试图按“好”的百分比对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

我已经阅读了多个答案,但是似乎都无法解决问题。我觉得我的数据表格格式可能是问题的一部分,但我尝试过多种方法。欢迎任何指导。


你能具体说明一下为什么你得到的输出不是你想要的吗?你希望可视化结果像你理想的例子那样,还是你只想更改y轴上的顺序? - NicolasH2
1个回答

5
你可以根据'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


这对我没有用,可能是因为我有三个级别。然而,fct_reorder2起了作用。https://forcats.tidyverse.org/reference/fct_reorder.html - meier_flo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接