我正在尝试将总计数添加到
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")
给了我这个:
我尝试添加
after_stat(count)
函数,这是我收到的错误消息:
中的错误: !计算统计数据时出现问题。 ℹ 第二层发生错误。 由geom_text()
中的错误引起: !setup_params()
必须仅具有 x 或 y 美学。 运行stat_bin()
查看错误发生的位置。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")
我不想每个箱内有 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()
必须仅具有 x 或 y 美学。 运行stat_count()
查看错误发生的位置。rlang::last_trace()
我打算放弃,直接在 Powerpoint 中手动添加数字。
正如我在评论中已经提到的,如果你想计算变量的总和,请使用
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")