如何解决R ggplot 排序百分比堆积条形图
我正在尝试根据“好”百分比对 ggplot 进行排序。下面是我正在使用的数据框。还有我现在得到的以及我理想中想要的。
library(ggplot2)
a <- c("Nevada","Maine","north Carolina","South Carolina","Texas","Rhode Island","Nevada","Rhode Island")
b <- c(0.81,0.72,0.65,0.55,0.45,0.35,0.19,0.28,0.65)
d <- c("Good","Good","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()
我目前的结果是:.
当前堆叠条形
理想情况下,我的结果是这样的:
期望输出
我已经阅读了多个答案,但是似乎没有任何效果。我认为我的数据表格式可能是问题的一部分,但是,我尝试了各种方法。感谢您提供任何指导。
解决方法
您可以根据 '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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。