ggplot中条形图上分类值的计数?

4

我是一个 R 的新手,如果这个问题很容易解决,请原谅我。我正在寻找一种方法,在 ggplot2 中显示分类值的计数,以生成条形图。

我已经准备了一些虚构的样本数据:

ID  Age SizeOfTumor RemovalSurgery
1   <30 Small   No
2   <30 Large   Yes
3   <30 Large   No
4   <30 Small   No
5   <30 Small   No
6   <30 Large   Yes
7   30-60   Large   No
8   30-60   Large   Yes
9   30-60   Large   Yes
10  30-60   Small   Yes
11  30-60   Small   Yes
12  30-60   Small   No
13  30-60   Large   No
14  30-60   Small   No
15  >60 Large   Yes
16  >60 Large   Yes
17  >60 Large   Yes
18  >60 Small   Yes
19  >60 Small   No
20  >60 Large   Yes

并使用以下代码绘制:

library(ggplot2)

ggplot(df, aes(x = SizeOfTumor, fill = RemovalSurgery)) + geom_bar(position = "fill") + facet_grid(~Age)

它生成了一个相当标准的条形图

我想做的是在保留百分比刻度的同时,将每个分类变量的数字添加到图表中。

  • 我查阅了一些类似的问题,并尝试了几种geom_text代码,但都没有成功。
  • 我认为区别可能在于我没有将y作为自己的列,只是将计数作为填充。

任何建议都将不胜感激。我不想手动输入所有标签。


你是否可以使用dput来代替复制文本?你所问的问题很简单,但是将你提供的示例数据读入R并不容易。 - Bishops_Guest
抱歉,如果我有任何未来的问题,我会记住这个建议。我倾向于从 .csv 文件中导入我的数据。 - R. G. B.
1个回答

5

在这种情况下,我建议你自己进行总结,而不是让ggplot为你总结。

library(ggplot2)
library(scales)
library(dplyr)

plot_data <- df %>% 
  count(SizeOfTumor, Age, RemovalSurgery) %>% 
  group_by(Age, SizeOfTumor) %>% 
  mutate(percent = n/sum(n))


ggplot(plot_data, aes(x = SizeOfTumor, y = percent, fill = RemovalSurgery)) + 
  geom_col(position = "fill") + 
  geom_label(aes(label = percent(percent)), position = "fill", color = "white", vjust = 1, show.legend = FALSE) +
  scale_y_continuous(labels = percent) +
  facet_grid(~Age)

我还使用了来自scales包的percentgeom_label中的y轴和文本进行格式化。

在此输入图片描述


成功把它搞成我想要的样子了!非常感谢。 - R. G. B.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接