简体   繁体   English

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

[英]R ggplot Sort Percent Stacked Bar Chart

I am attempting to sort a ggplot based on the "good" Percentage.我正在尝试根据“好”百分比对 ggplot 进行排序。 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所需 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.您可以过滤'Good'条件的数据,根据其降序分配因子水平,然后 plot 数据。

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM