首页 > 解决方案 > ggplot:条形顶部的百分比,但依靠 y-aes

问题描述

我正在尝试geom_bar在 ggplot 中使用来制作一个图表,该图表具有计数y-aes但在条形顶部的总组百分比。我的数据是cp.dat2,“orsok”列有 9 个因子变量。

我试过了

library(ggplot2)
library(scales)
ggplot(cp.dat2, aes(x = as.factor(orsok))) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
  scale_y_continuous(labels = percent)

并得到了这张照片: 在此处输入图像描述

我想要的是获得 y-aes 的计数,但将百分比保持在所有条形的顶部..

另外,我可以改变酒吧吗?例如,将 9.16% 的条放在前面(2.29% 的条在此)。

任何人都可以帮忙吗?

标签: rggplot2

解决方案


您可以使用 订购酒吧forcats::infreq()。您可以轻松地使用 y 位置的计数。这是自动完成的geom_bar(),而您必须使用 访问文本的计算统计信息after_stat()。请注意,它after_stat()取代了旧的..stat..符号并且更加灵活。

library(ggplot2)
library(scales)

cp.dat2 <- data.frame(
  orsok = sample(41:51, 100, replace = TRUE)
)

ggplot(cp.dat2, aes(x = forcats::fct_infreq(factor(orsok)))) +
  geom_bar() +
  geom_text(
    stat = "count",
    aes(y = after_stat(count),
        label = after_stat(percent(count / sum(count)))),
    vjust = -0.25
  )

reprex 包于 2021-04-20 创建(v1.0.0)


推荐阅读