gpt4 book ai didi

r - 如何使用 ggplot 在 R 中的多面堆叠条形图中使用不同的 geom_text() 标签?

转载 作者:行者123 更新时间:2023-12-04 13:08:41 24 4
gpt4 key购买 nike

我正在尝试将 facet_wrap 与堆叠条形图一起使用,并且我希望在条形图上使用标签来显示条形图每个部分的值。

以钻石数据集为例:

当只有一个图表时,我的 geom_text 代码工作正常,尽管对于较短的条形图来说有些局促:

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
geom_text(data = . %>%
group_by(cut, clarity) %>%
tally() %>%
ungroup() %>%
group_by(cut) %>%
ungroup(),
aes(y = n, label = n),
position = position_stack(0.5),
show.legend = FALSE)

Labeled bar plot without faceting

但是,当我添加分面时,所有标签都显示在所有单独的分面中:

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color) +
geom_text(data = . %>%
group_by(cut, clarity) %>%
tally() %>%
ungroup() %>%
group_by(cut) %>%
ungroup(),
aes(y = n, label = n),
position = position_stack(0.5),
show.legend = FALSE)

Faceted bar plot with replicated labeling

我怎样才能让标签只显示在相关栏上?

谢谢!

最佳答案

我认为您需要在 group_by + tally 中包含颜色,以便可以将其分配给正确的方面:

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color,scale="free_y") +
geom_text(data = . %>%
count(cut, clarity,color),
aes(y = n, label = n),size=1,
position = position_stack(0.5),
show.legend = FALSE)

enter image description here

关于r - 如何使用 ggplot 在 R 中的多面堆叠条形图中使用不同的 geom_text() 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com