我正在寻找以下问题的解决方案:
我有包含两个因子变量的数据EDU
and LEVEL
。可重现的数据样本在这里:
structure(list(EDU = structure(c(3L, 1L, 2L, 2L, 3L, 2L, 3L,
2L, 3L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 2L, 3L, 3L, 1L, 2L, 3L, 2L,
2L, 2L, 1L, 1L, 3L, 3L, 2L, 3L, 2L, 3L, 3L, 2L, 3L, 2L, 2L, 3L,
3L, 1L, 1L, 3L, 3L, 3L, 3L, 2L, 1L, 3L, 1L), .Label = c("A",
"B", "C"), class = "factor"), LEVEL = structure(c(3L, 3L, 4L,
2L, 4L, 3L, 1L, 2L, 2L, 1L, 3L, 2L, 3L, 2L, 3L, 3L, 4L, 2L, 2L,
4L, 1L, 2L, 3L, 3L, 1L, 4L, 2L, 3L, 1L, 1L, 2L, 3L, 1L, 2L, 1L,
4L, 3L, 1L, 4L, 3L, 4L, 1L, 4L, 2L, 4L, 1L, 1L, 4L, 3L, 1L), .Label = c("1",
"2", "3", "4"), class = "factor")), class = "data.frame", row.names = c(NA,
-50L))
使用这些数据我想绘制一个条形图ggplot2
显示分组变量EDU
x 轴上的累积百分比LEVEL
在 y 轴上。另外,我想添加第四个栏,其中包含LEVEL
but not分组依据EDU
——有点像“整体吧”。此外,我想在图中添加百分比标签,以便每个LEVEL
标有相应的相对频率,如下所示thread https://stackoverflow.com/questions/22231124/how-to-draw-stacked-bars-in-ggplot2-that-show-percentages-based-on-group或这个thread https://stackoverflow.com/questions/58744507/how-to-show-percentages-in-stacked-column-with-ggplot-geom-bar。老实说,我尝试使用 stackoverflow 中的不同解决方案来调整我的代码,以将百分比标签放入绘图中,因为有很多关于此主题的线程(特别是当涉及百分比标签时),但卡住了。到目前为止,我的ggplot2
代码如下所示:
library(tidyverse)
ggplot(df, aes(x=EDU, fill=LEVEL)) +
geom_bar(position="fill") +
scale_y_continuous(labels = scales::percent)
结果如下图:
到目前为止,该情节看起来不错。但如上所述,我的目标是添加百分比标签,可能是geom_text
除了现有的三个栏之外,还有第四个“整体栏”。对于百分比标签我也尝试制作prop.table
并添加带有相应道具的百分比标签和annotate
:
props <- prop.table(table(df$EDU, df$LEVEL), margin=1)
ggplot(df, aes(x=EDU, fill=LEVEL)) +
geom_bar(position="fill") +
scale_y_continuous(labels = scales::percent) +
annotate("text", x="A", y=.15, label=scales::percent(props[1,4])) +
annotate("text", x="B", y=.10, label=scales::percent(props[2,4])) +
annotate("text", x="C", y=.275, label=scales::percent(props[3,4])) +
annotate("text", x="A", y=.375, label=scales::percent(props[1,3])) +
annotate("text", x="B", y=.275, label=scales::percent(props[2,3])) +
annotate("text", x="C", y=.625, label=scales::percent(props[3,3])) +
annotate("text", x="A", y=.66, label=scales::percent(props[1,2])) +
annotate("text", x="B", y=.5, label=scales::percent(props[2,2])) +
annotate("text", x="C", y=.78, label=scales::percent(props[3,2])) +
annotate("text", x="A", y=.9, label=scales::percent(props[1,1])) +
annotate("text", x="B", y=.9, label=scales::percent(props[2,1])) +
annotate("text", x="C", y=.9, label=scales::percent(props[3,1]))
That results in the following plot:
这对我来说似乎很麻烦,特别是当我想创建多个绘图并且必须单独注释每个百分比时。在这里,问题可能是我如何设置 y 参数annotate
以“自动”方式让 R 为我定位标签。
不幸的是,关于“整体酒吧”问题,我不知道如何解决。
我很感激任何帮助!