R ggplot2:在尝试使用百分比时使用堆叠条形图时无法在 Y 轴上获得正确的标签

R ggplot2: Unable to get the right labels on Y-axis when using stacked barplot while trying to use percentages

我的数据是这样的:

如您所见,每个 ID 在每个 ID 的 0-10 之间的每个时间点都有 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))

输出: