【发布时间】:2026-01-07 01:40:01
【问题描述】:
我是 ggplot2(和 R)的新手,我正在尝试制作一个填充条形图,每个框中都有标签,指示组成该块的百分比。
这是我想添加标签的当前图的示例:
##ggplot figure
library(gpplot2)
library(scales)
#specify order I want in plots
ZIU$Affinity=factor(ZIU$Affinity, levels=c("High", "Het", "Low"))
ZIU$Group=factor(ZIU$Group, levels=c("ZUM", "ZUF", "ZIM", "ZIF"))
ggplot(ZIU, aes(x=Group))+
geom_bar(aes(fill=Affinity), position="fill", width=1, color="black")+
scale_y_continuous(labels=percent_format())+
scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray"))+
labs(x="Group", y="Percent Genotype within Group")+
ggtitle("Genotype Distribution", "by Group")
I would like to add labels centered in each box with the percentage that box represents
我尝试使用此代码添加标签,但它不断产生错误消息“错误:geom_text 需要以下缺失的美学:y”但我的情节没有 y 美学,这是否意味着我不能使用 geom_text? (此外,我不确定一旦 y 美学问题得到解决,geom_text 语句的其余部分是否会完成我想要的,在每个框中居中的白色标签。)
ggplot(ZIU, aes(x=Group)) +
geom_bar(aes(fill=Affinity), position="fill", width=1, color="black")+
geom_text(aes(label=paste0(sprintf("%.0f", ZIU$Affinity),"%")),
position=position_fill(vjust=0.5), color="white")+
scale_y_continuous(labels=percent_format())+
scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray"))+
labs(x="Group", y="Percent Genotype within Group")+
ggtitle("Genotype Distribution", "by Group")
另外,如果有人对消除 NA 值有任何建议,将不胜感激!我试过了
geom_bar(aes(fill=na.omit(Affinity)), position="fill", width=1, color="black")
但收到错误“错误:美学必须是长度 1 或与数据相同 (403):填充,x”
dput(sample)
structure(list(Group = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L), .Label = c("ZUM", "ZUF", "ZIM", "ZIF"), class = "factor"),
StudyCode = c(1, 2, 3, 4, 5, 6, 20, 21, 22, 23, 143, 144,
145, 191, 192, 193, 194, 195, 196, 197, 10, 24, 25, 26, 27,
28, 71, 72, 73, 74, 274, 275, 276, 277, 278, 279, 280, 290,
291, 292), Affinity = structure(c(3L, 2L, 1L, 2L, 3L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 3L, 1L, 1L, 1L, 3L,
2L, 1L, 2L, 2L, 1L, 2L, 2L, 3L, 3L, 2L, 1L, 3L, 2L, 1L, 3L,
3L, 2L, 2L, 2L), .Label = c("High", "Het", "Low"), class = "factor")), .Names = c("Group",
"StudyCode", "Affinity"), row.names = c(NA, 40L), class = c("tbl_df",
"tbl", "data.frame"))
非常感谢!
【问题讨论】:
-
我的意思是“条形”标签,而不是上面评论中的“盒子”标签。
-
嗨@eipi10,我在尝试解决我的问题时查看了这两个帖子,但在每种情况下,它们的情节都有一种美感,而我的情节没有,因此会产生错误消息。因为我的图表是“整体的一部分”,所以我不能在 y 上放任何东西——这是否意味着我根本不能使用 geom_text?
-
您可以发布您的数据样本吗?将
dput(data_sample)的输出粘贴到您的问题中。 -
@eipi10 已添加!让我知道这是否有帮助。谢谢!
标签: r ggplot2 bar-chart labels