如何使用ggplot geom_bar在堆积列中显示百分比?

我正在尝试在堆积的条形图中添加百分比标签。我可以添加什么到geom_bar中以显示堆积条形图中的百分比标签?

这是我的数据

myresults=data.frame(
    manipulation=rep(c(-20,-10,10,20,-20,20)),variable=rep(c("a","a","f","l","l")),value=c(73,83,76,75,78,261,301,344,451,599,866,816,780,674,523))

This is my bar chart,without percentage labels.

我对此一无所知。我在“ gglot堆积条形百分比标签”上进行了搜索,发现可以使用“ + geom_text(stat =“ count”)“来添加百分比标签。

但是,当我在ggplot geom_bar中添加+ geom_text(stat =“ count”)时,R表示“错误:不得将stat_count()用于美观。”我试图弄清楚什么是y美学,但是还不是很成功。

这就是我所做的:

mydata <- ggplot(myresults,aes(x=manipulation,y=value,fill=variable))

mydata + geom_bar(stat="identity",position="fill",colour="black") + scale_fill_grey() + scale_y_continuous(labels=scales::percent) + theme_bw(base_family="Cambria") + labs(x="Manipulation",y=NULL,fill="Result") + theme(legend.direction="vertical",legend.position="right")
haifeng897 回答:如何使用ggplot geom_bar在堆积列中显示百分比?

您可以在Adding percentage labels to a bar chart in ggplot2中执行与接受的答案类似的操作。主要区别在于您的值是堆积的(“ stacked”),而在该示例中,它们是并排的(“ dodged”)

输入百分比列:

margin-bottom

现在我们将其绘制:

myresults_pct <- myresults %>% 
group_by(manipulation) %>% 
mutate(pct=prop.table(value))

geom_text中的重要参数是position =“ stacked”,并随心所欲地上下移动标签。 (我为糟糕的文字颜色提前表示歉意。)。

enter image description here

,

您可以尝试创建geom文本的位置并将其放在栏上:

mydata[,label_ypos := cumsum(value),by = manipulation]

ggplot(myresults,aes(x=manipulation,y=value,fill=variable)) + 
geom_bar(stat="identity",position="fill",colour="black") +
geom_text(aes(y=label_ypos,label= paste(round(rent,2),'%')),vjust=2,color="white",size=3.5) +
scale_y_continuous(labels = scales::percent) +
labs(x = "Manipulation",y=NULL,fill="Result") +
theme_bw(base_family = "Cambria") +
theme(legend.direction = "vertical",legend.position = "right") +
scale_fill_grey() 
本文链接:https://www.f2er.com/3146552.html

大家都在问