我有一個 df,我打算將其可視化為堆積百分比條形圖,堆疊按降序排列。df 包含成比例的值,并已轉換為長格式。下面是基于我正在使用的真實資料的一些虛擬資料的代表。
df<- data.frame(ID=c("A","B","C","D","E"),
a1=c((0.452),(0.558),(0.554),(0.484),(0.661)),
a2=c((0.326),(0.373),(0.465),(0.434),(0.499)),
a3=c((0.450),(0.481),(0.613),(0.473),(0.504)),
a4=c((0.561),(0.681),(0.633),(0.504),(0.723)))
dflong<-df%>%
pivot_longer(!ID, names_to="aa", values_to="prop")
dflong$ID<-as.factor(dflong$ID)
# A tibble: 15 × 3
ID aa prop
<fct> <chr> <dbl>
1 A a1 0.452
2 A a2 0.326
3 A a3 0.45
4 A a4 0.561
5 B a1 0.558
6 B a2 0.373
7 B a3 0.481
8 B a4 0.681
9 C a1 0.554
10 C a2 0.465
11 C a3 0.613
12 C a4 0.633
13 D a1 0.484
14 D a2 0.434
15 D a3 0.473
dflong %>%
ggplot(aes(x=ID,y=prop, fill=reorder(aa,-prop)))
geom_col(position ="fill", data=dflong%>%filter(ID=="A"))
geom_col(position ="fill", data=dflong%>%filter(ID=="B"))
geom_col(position ="fill", data=dflong%>%filter(ID=="C"))
geom_col(position ="fill", data=dflong%>%filter(ID=="D"))
geom_col(position ="fill", data=dflong%>%filter(ID=="E"))
geom_text(aes(label=scales::percent(prop)),
position=position_fill(vjust=.5), size=3, colour="black")
scale_y_continuous(labels = NULL, breaks = NULL)
scale_fill_brewer(palette="GnBu",
name="")
coord_flip()
theme_minimal()
theme(legend.position = "bottom",
legend.direction = "horizontal")
labs(caption="",
x="",
y="")
我的問題是生成的圖將始終在變數“C”中的兩個值之間切換,即堆疊條形圖將交換 C-a1 和 C-a3 的值。情節的影像將清楚地說明問題。

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523476.html
標籤:rggplot2
