首页 > 解决方案 > 当轴是离散的时,如何轻推 geom_text_repel 中段的起点?

问题描述

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适用于 iris 示例的参数,但不幸的是,当点彼此靠近时它不起作用。

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)

标签: rggplot2ggrepel

解决方案


也许这就是你要找的。即使使用离散轴ggplot2在引擎盖下使用数字,即第一个类别位于 1,第二个位于 2,......因此,您可以x像使用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")


推荐阅读