在ggplot2中向geom_bar(stat = "identity")添加总计数标签

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

我正在尝试将总计数添加到

geom_bar
图中,其中
stat = "identity"
中有命令 (
ggplot2
)。我在 stat = "count" 函数和
label = after_stat(count)
函数方面遇到问题。我正在通过 R Studio 运行 R 版本 4.3.1。

没有任何计数的基本代码:

library(ggplot2)

ggplot(gold, aes(x=Site, y=APIDAE, fill=Site, colours))+
  geom_bar(stat = "identity")+
  scale_fill_manual(name = "Sites", values = gold_cols)+
  ylab(label = "Famille apidae")+
  ylim(0, 50)+
  ggtitle("Présence Apidae entre sites")

给了我这个:

enter image description here

我尝试添加

after_stat(count)
函数,这是我收到的错误消息:

geom_text()
中的错误: !计算统计数据时出现问题。 ℹ 第二层发生错误。 由
setup_params()
中的错误引起: !
stat_bin()
必须仅具有 x 或 y 美学。 运行
rlang::last_trace()
查看错误发生的位置。

我也尝试过这个:

ggplot(gold, aes(x=Site, y=APIDAE, fill=Site, colours))+
  geom_bar(stat = "identity")+
  scale_fill_manual(name = "Sites", values = gold_cols)+
  ylab(label = "Famille apidae")+
  ylim(0, 50)+
  geom_text(
    aes(label = APIDAE),
    colour = "white", size = 3,
    vjust = 1.5, position = position_dodge(.9)
  )+
  ggtitle("Présence Apidae entre sites")

enter image description here

我不想每个箱内有 4 个值,我想要箱内的总和。

我尝试了

stat = "count"
但运气不佳:

ggplot(gold, aes(x=Site, y=APIDAE, fill=Site, colours))+
geom_bar(position = "dodge")+
  geom_text(
    stat = "count",
    aes(
      label = after_stat(count)
      ),
    position = position_dodge(),
    color = "black",
    size = 8,
    vjust = -0.2
  )+
  scale_fill_manual(name = "Sites", values = gold_cols)+
  ylab(label = "Famille apidae")+
  ylim(0, 50)+
  ggtitle("Présence Apidae entre sites")

给我这个错误:

geom_bar()
中的错误: !计算统计数据时出现问题。 ℹ 第一层发生错误。 由
setup_params()
中的错误引起: !
stat_count()
必须仅具有 x 或 y 美学。 运行
rlang::last_trace()
查看错误发生的位置。

我打算放弃,直接在 Powerpoint 中手动添加数字。

r ggplot2 geom-bar geom-text
1个回答
0
投票

正如我在评论中已经提到的,如果你想计算变量的总和,请使用

stat_summary
stat="count"
将计算计数(又称为观察数)并将结果映射到
y
,即,当变量映射到
y
时它不起作用,并且会导致错误。

使用一些基于

ggplot2::mpg
数据集的虚假示例数据:

library(ggplot2)

# Make example data
gold <- mpg |>
  dplyr::count(class, trans) |>
  dplyr::rename(Site = class, APIDAE = n)

ggplot(gold, aes(x = Site, y = APIDAE, fill = Site)) +
  geom_bar(stat = "identity") +
  stat_summary(
    aes(label = after_stat(y)),
    fun = "sum", geom = "text", vjust = 0,
    position = position_nudge(y = 1)
  ) +
  # scale_fill_manual(name = "Sites", values = gold_cols) +
  # ylim(0, 50) +
  ylab(label = "Famille apidae") +
  ggtitle("Présence Apidae entre sites")

但是,也许最简单的方法是在将数据集传递到 ggplot2 之前正确聚合数据集。这样您就可以添加标签而无需

stat_summary()
:

gold <- gold |>
  dplyr::summarise(APIDAE = sum(APIDAE), .by = Site)

ggplot(gold, aes(x = Site, y = APIDAE, fill = Site)) +
  geom_col() +
  geom_text(aes(label = APIDAE),
    vjust = 0,
    position = position_nudge(y = 1)
  ) +
  # scale_fill_manual(name = "Sites", values = gold_cols) +
  # ylim(0, 50) +
  ylab(label = "Famille apidae") +
  ggtitle("Présence Apidae entre sites")

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