R语言 在ggplot2中的条顶部绘制计数

lyr7nygr  于 2023-03-27  发布在  其他
关注(0)|答案(2)|浏览(176)

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

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))

我需要把计数加到条的顶部。我该怎么做呢?

vc9ivgsu

vc9ivgsu1#

这在ggplot 3.4.0November 2022)中发生了变化。如果你搜索这方面的问题,你会看到很多使用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
    )

kkih6yb8

kkih6yb82#

我喜欢得到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))

相关问题