gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:37:13 26 4
gpt4 key购买 nike

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

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

我试过:

  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"
)

enter image description here

关于r - 我可以使用 geom_text_repel 控制相同值的多个标签的顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62516632/

26 4 0