当轴是离散的时,如何在 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,nudge_x = .5
  ) +
  geom_segment(
    aes(xend = name,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",color = label),size = 10
  ) +
  geom_text_repel(
    aes(label = label,y = y0 + 0.5),nudge_x = 1/8,size = 5,point.padding = 1.25,hjust = 0
  ) +
  ylim(-12*2,12*3)

解决方法

也许这就是您要找的。即使使用离散轴 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
  )

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...