在 ggplot2 中的条形图上绘制计数

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

我有一个看起来像这样的数据集:

Smoking population
1      yes     group1
2      yes     group3
3      yes     group2
4       no     group1
5       no     group1
6      yes     group3
7       no     group2
8      yes     group2
9      yes     group3
10      no     group1
11      no     group1
12      no     group3
13     yes     group2
14      no     group2
15      no     group1
16     yes     group1
17     yes     group2
18      no     group3
19      no     group3
20     yes     group1
21      no     group3

我正在尝试在 x 轴上绘制人口并在 y 轴上计算是和否,如下所示:

library(tidyverse)
    df %>%
      ggplot(aes(x = population , color = Smoking, fill = Smoking)) +
      geom_bar(position = 'dodge')+ 
      theme(axis.text.x = element_text(angle=90, vjust=.5, hjust=1))

我需要在条形图的顶部添加计数。我该怎么做?

r ggplot2 geom-bar
2个回答
1
投票

这在

ggplot 3.4.0
2022 年 11 月)发生了变化。如果您搜索关于此的问题,您会看到很多使用
stat()
..count..
.

的代码

但是,这在

3.4.0
中被弃用了。您现在可以使用
after_stat(count)
来计算计数:

ggplot(df, aes(x = population, color = Smoking, fill = Smoking)) +
    geom_bar(position = "dodge") +
    theme(axis.text.x = element_text(angle = 90, vjust = .5, hjust = 1)) +
    geom_text(
        stat = "count",
        aes(
            label = after_stat(count)
        ),
        position = position_dodge(),
        color = "black",
        size = 8,
        vjust = -0.2
    )


0
投票

我喜欢在

geom_text
内得到计数,就像@SamR 的回答一样。

另一种方法是在调用

ggplot
之前计算计数,然后在
geom_text

中使用它们
df %>% 
  mutate(count_data = n(), .by = c(population, Smoking)) %>% 
  ggplot(aes(x = population , color = Smoking, fill = Smoking)) + 
  geom_bar(position = 'dodge') + 
  geom_text(aes(population, count_data, label = count_data), 
    vjust=-.5, color="black", position = position_dodge(.9)) + 
  theme(axis.text.x = element_text(angle=90, vjust=.5, hjust=1))

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