繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM