使用 facet_grid() 调整条形图的小数百分比

Adjusting percentage decimals for a bar plot with facet_grid()

我有以下行:

p1 <- ggplot(mtcars, aes(x= cyl)) + geom_bar(aes(fill = vs), stat = "count") + geom_text(aes(label = scales::percent(..prop..), ymax= ..prop..), stat = "count", vjust = -0.5) +  theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)

给出了这个情节。这是一个图,我想在 y 轴上保留计数整数,但我希望在每个条形图上方显示百分比。

我想编辑每个条形图的小数位数。但是,当使用下面的行时:

p2 <- ggplot(mtcars, aes(x= cyl)) + geom_bar(aes(fill = vs), stat = "count") + geom_text(aes(label = scales::percent(round((..count..)/sum(..count..),1)), ymax= ((..count..)/sum(..count..))), stat="count",  vjust = -.25) + theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)

百分比现在关闭(见下文),显示整个地块的百分比,而不是分离的小平面。有没有办法在不影响数字的情况下四舍五入百分比?

scales::percent中有一个精度选项:

p1 <- ggplot(mtcars, aes(x= cyl)) + 
geom_bar(aes(fill = vs), stat = "count") + 
geom_text(aes(label = scales::percent(..prop..,accuracy=2)), 
stat = "count", vjust = -0.5) +  
theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)

可以在scales::percent函数中使用accuracy = 2

p1 <- ggplot(mtcars, aes(x= cyl)) + geom_bar(aes(fill = vs), stat = "count") +
  geom_text(aes(label = scales::percent(..prop.., accuracy = 2), ymax= ..prop..), stat = "count", vjust = -0.5) + 
  theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)
p1