如何使用 stat="count" 在 ggplot2 中用计数或百分比标记条形图?

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

我正在尝试生成带有数据标签的堆积柱形图。

我能够生成图表,但无法找到输入数据标签的方法。我已经尝试过

geom_text()
但它一直要求我输入 y 标签(如果你看到 ggplot 代码不存在)。我也尝试添加
geom_text(stat = "count")
但这也给了我一个错误:

“错误:geom_text 需要以下缺失的美感:y 和标签”。

PS - 我知道我需要将 y 轴重命名为百分比。我也在想办法如何拥有更多对比色

ggplot(property,
       aes(x=Bedrooms.New, fill=Property.Type.)) + 
  geom_bar(position = "fill") + 
  scale_x_discrete(name = "Number of Bedrooms", 
                   limits = sort(factor(unique(property$Bedrooms.New))))

我在下面添加了一张图片来查看我现在的输出是什么!

r ggplot2 geom-bar geom-text
2个回答
13
投票

正如错误消息告诉您的那样,

geom_text
需要
label
aes。在您的情况下,您想用一个变量来标记条形,该变量不是数据集的一部分,而是由
stat="count"
计算,即
stat_count

计算变量可以通过

..NAME_OF_COMPUTED_VARIABLE..
访问。 ,例如要获取计数,请使用
..count..
作为变量名称。顺便说一句:计算变量的列表可以在 stat 或 geom 的帮助包中找到,例如
?stat_count

更新:

ggplot2 3.4.0
中已弃用点点表示法。相反,我们可以或应该使用
after_stat
,即使用例如
after_stat(count)
而不是
..count..

使用

mtcars
作为示例数据集,您可以像这样标记
geom_bar

library(ggplot2)

ggplot(mtcars, aes(cyl, fill = factor(gear))) +
  geom_bar(position = "fill") +
  geom_text(aes(label = after_stat(count)),
    stat = "count", position = "fill"
  )

还有两个注意事项:

  1. 要获得正确的标签位置,您必须设置

    position
    参数以匹配
    geom_bar
    中使用的参数,例如
    position="fill"
    在你的情况下。

  2. 虽然计数非常简单,但用百分比标记是一个不同的问题。默认情况下

    stat_count
    按组计算百分比,例如由通过
    fill
    aes 设置的组。这些可以通过
    after_stat(prop)
    访问。如果您希望以不同的方式计算百分比,则必须手动执行。

举个例子,如果您希望每条柱的百分比总和为 100%,可以使用

after_stat
ave
(计算每组的百分比)来实现,如下所示:

library(ggplot2)

ggplot(mtcars, aes(cyl, fill = factor(gear))) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = after_stat(
      scales::percent(
        ave(count, x, FUN = function(x) x / sum(x))
      )
    )),
    stat = "count", position = "fill"
  )


0
投票

在上面的答案中添加后续内容,因为这个答案通常可以让我完成 90% 的任务,但我永远不记得如何做:

  • 将标签居中 (
    position_fill(vjust = 0.5)
    )
  • 让百分比标签变得漂亮(
    scales::percent()
    )
library(ggplot)

ggplot(mtcars, aes(cyl, fill = factor(gear)))+
  geom_bar(position = "fill") +
  geom_text(aes(label = scales::percent(..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)])), stat = "count", position = position_fill(vjust = 0.5))

这是提前预先计算的替代方案:

mtcars %>% 
  count(gear, cyl) %>% 
  group_by(cyl) %>% 
  mutate(perc = n / sum(n)) %>% 
  ggplot(aes(cyl, perc, fill = factor(gear)))+
  geom_col(position = "fill") +
  geom_text(aes(label = scales::percent(perc)), position = position_fill(vjust = 0.5))
© www.soinside.com 2019 - 2024. All rights reserved.