![](/img/trans.png)
[英]ggplot2 barplot - adding percentage labels inside the stacked bars but retaining counts on the y-axis
[英]R ggplot2: Unable to get the right labels on Y-axis when using stacked barplot while trying to use percentages
我的數據是這樣的:
正如您所看到的,每個 ID 有 10 個觀察值,每個 ID 的每個時間點都有特定的“狀態”,介於 0-10 之間。
id year status
1 20 0 2
2 20 1 2
3 20 2 2
4 20 3 5
5 20 4 5
6 20 5 5
7 20 6 5
8 20 7 5
9 20 8 5
10 20 9 5
11 20 10 5
12 35 0 2
13 35 1 5
14 35 2 5
15 35 3 5
16 35 4 5
17 35 5 5
18 35 6 5
19 35 7 5
20 35 8 5
所以,這就是我最初的繪圖命令的方式
axs=dat %>% group_by(year)%>% ggplot(aes(x=year,fill = factor(status))) +
+ geom_bar(position = "stack", width = 1) + stat_count()+
+ scale_fill_hue(labels = c("Not listed", "Listed", "Removed", "Given", "Wasted")) +
+ labs(title= "Trajectory ",x = "time", y = "Percent ", fill = "Status") + scale_x_continuous(breaks = seq(0,10,1))
然后我想將Y軸轉換成百分比圖,所以我的命令改為:
axs + scale_y_continuous(labels=function(x){round(x*100/length(unique(dat$id)))})
然后我將其修改為:
axs + scale_y_continuous(labels=function(x){round(x*100/length(unique(dat$id)))}, breaks=c(0,100,25))
當我輸入 break= seq(0,100,25)) 時,我得到了相同的數字。 當我在 scale_y_continuous 命令中使用中斷時,我在 Y 軸上只得到 0。 如果我不使用它,那么我在 Y 軸上得到 101,我試圖消除它(因為它在 X 軸上的百分比)。
有人能告訴我如何解決這個問題嗎? 將不勝感激,謝謝,沙洛姆
嘗試這個:
axs=dat %>% group_by(year)%>% ggplot(aes(x=year,fill = factor(status))) +
geom_bar(position = "stack", width = 1) + stat_count()+
scale_fill_hue(labels = c("Not listed", "Listed", "Removed", "Transplanted", "Died")) +
labs(title= "Trajectory in less than 65 yrs age",x = "Years after graft failure", y = "Percent of patients", fill = "Status") +
scale_y_continuous(labels = function(x) paste0(100*x/max(x),'%'))+
scale_x_continuous(breaks = seq(0,10,1))
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.