在geom_segment中避免线条重叠

编程语言 2026-07-09

我想让geom_segment的线在我的物种组的点之间不重叠,就像上方的索引变量(SPI2)那样。中心点应该是黑点,表示所有组的相关性,而颜色则显示各组的相关性。

我不是说像 position_doge() 那样平行。仔细看这些线,它们的颜色与点并不匹配。基本上,我希望前面的部分更短。

示例数据与代码:

cor_join <- data.frame(
  index = c("SPEI1","SPEI1","SPEI1","SPEI1",
           "SPI1","SPI1","SPI1","SPI1",
           "SPI2","SPI2","SPI2","SPI2"),
  species = c("Pine","Oak","Birch","Spruce",
              "Pine","Oak","Birch","Spruce",
              "Pine","Oak","Birch","Spruce"),
  cor_species = c(0.8, 0.88, 0.94, 0.71,
                  0.94, 0.71, 0.37, 0.85,
                  0.21, 1, 0.4, 0.42),
  cor_all = c(0.7584332, 0.7584332, 0.7584332, 0.7584332,
              0.7819371, 0.7819371, 0.7819371, 0.7819371,
              0.8596302, 0.8596302, 0.8596302, 0.8596302))

ggplot(cor_join, aes(x = cor_all, xend = cor_species, y = index)) +
  geom_segment(aes(color = species), lwd=1) +
  geom_point(aes(x = cor_species, color = species)) +
  geom_point(aes(x = cor_all), color = "black", size = 2)+
  theme_bw()

解决方案

你需要基于它们与 cor_all距离 对线段进行排序。

library(ggplot2)
library(dplyr)

cor_join %>%
  mutate(dist = abs(cor_all - cor_species)) %>% 
  arrange(desc(dist)) %>% 
ggplot(aes(x = cor_all, xend = cor_species, y = index)) +
  geom_segment(aes(color = species), linewidth = 1) +
  geom_point(aes(x = cor_species, color = species), size = 3) +
  geom_point(aes(x = cor_all), color = "black", size = 2) +
  theme_bw()

创建于2026-04-22,使用 reprex v2.1.1

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章