我可以使用 geom_text_repel 控制同一值的多个标签的顺序吗?

Can I control the order of multiple labels for the same value using geom_text_repel?

我正在绘制一个图,其中多个数据点具有相同的坐标。默认情况下,标签全部重叠,但使用 geom_text_repel with direction = "y",我可以垂直 space 它们出来。

但是,每次我生成绘图时,它都会为标签选择一个新的顺序。我希望它们根据值进行排序。

我试过:

  1. 使用“排列”以我希望看到标签的顺序对数据帧进行排序(这似乎没有效果)
  2. 尝试使用“nudge_y”按照我想要的顺序重新排列标签。这似乎改变了情节 - 它确实“推动”了他们 - 但它并没有推动他们进入正确的顺序!

这是重现问题的示例代码。基本上,我希望最终情节按“顺序”值排序 - 因此,对于“10”上的三个数据点,顺序应该是 Ayala、Zoe、JL,而对于“5”上的两个数据点,顺序应该是Raph, Oona.

我对绘图进行了颜色编码,以明确它们的顺序 - 对于每个值,最浅的蓝色应该在顶部,最暗的蓝色应该在底部。

library(tidyverse)
library(ggrepel)

name <- c("Oona","Sam","Raph", "JL", "Zoe","Ayala")
year <- rep(c("2016"),6)
value <- c(5,15,5,10,10,10)  #The value I'm plotting
order <- c(5,-10,10,-5,0,5)  #The value I want to order the labels by

test_df <- bind_cols(name = name, year = year, value = value, order = order) %>% 
  arrange(-value, -order) #arranging the df doesn't seem to affect the order on the plot at all, I just do it so I can easily preview the df in the correct order

  
ggplot(data = test_df, aes(x = year, y = value, group = name)) +
  geom_point(aes(color = order)) +
  geom_text_repel(data = test_df, 
                  aes(label = name, color = order), 
                  hjust = "left", 
                  nudge_y = order, #This is where I'm trying to "nudge" them into the right order
                  nudge_x = -.45,
                  direction = "y") 

我认为您的顺序列中的值对于提供的 y 轴刻度来说太大了,因此 geom_text_repel 正在做幕后工作以使其完全适合,并更改了顺序过程中的标签。当我将订单列缩小到原来大小的五分之一时,效果很好。

test_df$order <- test_df$order*1/5
  
ggplot(data = test_df, aes(x = year, y = value, group = name)) +
  geom_point(aes(color = order)) +
  geom_text_repel(data = test_df, 
                  aes(label = name, color = order),
                  hjust = "left",
                  nudge_y = test_df$order,
                  nudge_x = -.45,
                  direction = "y"
                  )