library(tidyverse)
library(ggrepel)
df <- iris %>%
pivot_longer(starts_with("Sepal")) %>%
group_by(Species, name) %>%
summarise(
y0 = min(value),
y1 = max(value)
)
我经常使用ggrepel
包来添加标签和注释我的ggplots,但有时外观可能有点难以调整。作为这个问题的一个例子,我用众所周知的 ìris
数据制作了以下愚蠢的图。
df %>%
ggplot(aes(x = name)) +
geom_segment(
aes(xend = name, y = y0, yend = y1, color = Species), size = 10
) +
geom_text_repel(
aes(label = Species, y = y1), direction = "y", nudge_x = .5
)
我正在寻找一种方法来调整 ggrepel 箭头的起始位置,以便它们从段的右侧开始,而不是从中间开始。当然,一种解决方法是将片段放置在箭头顶部:
df %>%
ggplot(aes(x = name)) +
geom_text_repel(
aes(label = Species, y = y1), direction = "y", nudge_x = .5
) +
geom_segment(
aes(xend = name, y = y0, yend = y1, color = Species), size = 10
)
但这只有在没有任何透明度的情况下才有效,所以我想知道是否还有其他解决方案。我想我正在寻找 nudge_x_start
或类似的东西。
编辑:@stefan 建议使用适用于虹膜示例的 point.padding
参数,但不幸的是,当点彼此靠近时,它不起作用。
df2 <- enframe(month.name, "y0", "label") %>%
mutate(y1 = y0 + 1)
df2 %>%
ggplot(aes(x = "month")) +
geom_segment(
aes(xend = "month", y = y0, yend = y1, color = label), size = 10
) +
geom_text_repel(
aes(label = label, y = y0 + 0.5), direction = "y", nudge_x = 1/8,
size = 5, point.padding = 1.25, hjust = 0
) +
ylim(-12*2, 12*3)
最佳答案
也许这就是您正在寻找的。即使使用离散轴,ggplot2
在底层也使用数字,即第一个类别位于 1,第二个类别位于 2,...因此您可以“微调”内部的 x
aes 就像您对 y 所做的那样。为此,您必须将映射到 x
的分类变量转换为数字:
library(tidyverse)
library(ggrepel)
df <- iris %>%
pivot_longer(starts_with("Sepal")) %>%
group_by(Species, name) %>%
summarise(
y0 = min(value),
y1 = max(value)
)
#> `summarise()` has grouped output by 'Species'. You can override using the `.groups` argument.
df %>%
ggplot(aes(x = name)) +
geom_segment(
aes(xend = name, y = y0, yend = y1, color = Species),
size = 10
) +
geom_text_repel(
aes(label = Species, y = y1, x = as.numeric(factor(name)) + .06),
direction = "y", nudge_x = .5
)
df2 <- enframe(month.name, "y0", "label") %>%
mutate(y1 = y0 + 1)
df2 %>%
ggplot(aes(x = "month")) +
geom_segment(
aes(xend = "month", y = y0, yend = y1, color = label), size = 10
) +
geom_text_repel(
aes(label = label, y = y0 + 0.5, x = as.numeric(factor("month")) + .025), direction = "y", nudge_x = .5,
size = 5, hjust = 0
) +
ylim(-12*2, 12*3) +
guides(color = "none")
关于r - 当轴离散时,如何微移 geom_text_repel 中线段的起点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68196233/