百分比标签未显示在条形图上

时间:2020-06-19 09:54:01

标签: r ggplot2 bar-chart percentage geom-bar

我正在尝试绘制带有百分比标签的条形图。但是,这些百分比并不令人讨厌地显示在每个相应条的上方,而是按照您在下面看到的方式放置。有谁知道是什么原因造成的以及如何解决?

我使用的代码是:

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

给出

Barplot of tcars

请注意,我想在y轴上保持计数。

1 个答案:

答案 0 :(得分:1)

我们可以使用ymaxvjust

library(ggplot2)
ggplot(mtcars, aes(x= cyl)) + 
geom_bar(aes(fill = vs), stat = "count") + 
geom_text(aes(ymax= ..prop.., label = scales::percent(..prop..)), stat = "count", vjust = -.1) + 
theme_classic() + 
ylab("Count") + 
facet_grid(vs ~ .)

enter image description here