小编Sar*_*rah的帖子

使用 geom_text 在填充条形图中居中标签

我是 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")
Run Code Online (Sandbox Code Playgroud)

我想添加以每个框为中心的标签以及该框代表的百分比

我尝试使用此代码添加标签,但它不断生成错误消息“错误: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")
Run Code Online (Sandbox Code Playgroud)

另外,如果有人有消除 NA …

label r bar-chart ggplot2

4
推荐指数
1
解决办法
7420
查看次数

标签 统计

bar-chart ×1

ggplot2 ×1

label ×1

r ×1