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

问题描述 投票:1回答:2

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

This is my bar chart, without percentage labels.

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

但是当我在ggplot geom_bar中添加+ geom_text(stat =“ count”)时,R表示“错误:stat_count()不能与y美学一起使用。”我试图弄清楚什么是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")
r ggplot2 geom-bar
2个回答
0
投票

您可以尝试创建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() 

0
投票

与提供的@Tjebo示例相比,您拥有不同类型的数据。在该示例中,计数和百分比是在运行过程中(绘制时)即时计算的,而您已经在“值”列中进行了计算]

我没有您的数据,但是我尝试模拟接近的数据,并演示如何添加百分比。希望它对您有用,如果没有,您需要丢弃数据,以便其他人也可以提供帮助。

# simulate data
myresults = data.frame(
   manipulation=rep(c(-10,0,10),each=3),
   value = c(10,20,70,15,25,60,30,40,30)/100,
   variable = rep(c("a","f","l"),3))

# your plot previously
# i have problems with Cambria so omitted that
# i removed the position="fill" for geom_bar, you don't need that
mydata <- ggplot(myresults, aes(x=manipulation, y=value, fill=variable))

BARPLOT <- mydata + geom_bar(stat="identity", colour="black") + 
scale_fill_grey() +  
labs(x = "Manipulation", y=NULL, fill="Result") +
theme(legend.direction = "vertical", legend.position = "right")

您现在应该有类似的东西,除了yaxis不是百分比。现在我们添加文本,

BARPLOT + geom_text(aes(label=round(100*value,1)),position="stack",vjust=+2.5,col="firebrick")+
scale_y_continuous(labels = scales::percent)

geom_text中的重要参数是position =“ stacked”,因此,可以使用与geom_bar相同的方式插入文本,并进行调整以向上或向下移动标签。 (我为文字颜色过深表示歉意。)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.