gpt4 book ai didi

r - 如何在 geom_text 中使用 position_dodge with preserve = 'single'?

转载 作者:行者123 更新时间:2023-12-05 04:36:44 31 4
gpt4 key购买 nike

我正在尝试用 geom_text 标记条形图。它在大多数情况下适用于 position_dodge,但在某些情况下,我得到的图看起来像这样。我使用 preserve = 'single' 绕过宽条,但相应的 geom_text 不会移动以匹配条。我已经让它与 position_dodge2() 一起工作,但我喜欢在这种情况下 position_dodge 中的条一直对齐到左侧的方式。

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + 
geom_bar(aes(y = ..count..), stat = 'count', position = position_dodge(preserve = 'single')) +
geom_text(aes(label = ..count..), stat = 'count', position = position_dodge(width = 1))

enter image description here

因子 8 上的“14”对齐到中间而不是左边。有没有简单的解决方法?

如果我切换到 position_dodge2 并使用 preserve = 'single' 它会起作用,但条形图以 x 轴为中心。在 position_dodge 中,条形图左对齐,缺失值右对齐。如果有一种方法可以在不牺牲对齐方式的情况下使用 position_dodge2,那也是可行的。

enter image description here

最佳答案

我不喜欢这个,但一种可能性是用 tidyr::complete 枚举可能性,这样任何遗漏的都会得到一个 NA,它将以你想要的间距绘制:

library(tidyverse)
mtcars %>%
count(cyl = factor(cyl), vs = factor(vs)) %>%
complete(cyl, vs) %>% # creates "8 cyl / 1 vs / NA n" row
ggplot(aes(cyl, n, fill = vs)) +
geom_col(position = position_dodge(preserve = 'single')) +
geom_text(aes(label = n), position = position_dodge(width = 1))

enter image description here

关于r - 如何在 geom_text 中使用 position_dodge with preserve = 'single'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70775965/

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