簡體   English   中英

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

我目前的結果是:。

當前堆積條

在此處輸入圖像描述

理想情況下,我的結果是這樣的:

所需 Output

在此處輸入圖像描述

我已經閱讀了多個答案,但是似乎沒有任何效果。 我認為我的數據表格式可能是問題的一部分,但是,我嘗試了各種方法。 任何指導表示贊賞。

您可以過濾'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