作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试用 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))
因子 8 上的“14”对齐到中间而不是左边。有没有简单的解决方法?
如果我切换到 position_dodge2
并使用 preserve = 'single'
它会起作用,但条形图以 x 轴为中心。在 position_dodge
中,条形图左对齐,缺失值右对齐。如果有一种方法可以在不牺牲对齐方式的情况下使用 position_dodge2
,那也是可行的。
最佳答案
我不喜欢这个,但一种可能性是用 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))
关于r - 如何在 geom_text 中使用 position_dodge with preserve = 'single'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70775965/
我是一名优秀的程序员,十分优秀!