按组绘制一些耦合数据点之间的连接线

问题描述 投票:0回答:1

在我的相关ggplot中,我想在一些数据点对之间添加一些额外的“迷你回归线”。

我有10个物种,观察过两次(2010年和2014年)。

set.seed(42)
obs_2010 <- runif(10, min=1, max=20)
obs_2014 <- runif(10, min=1, max=20)
species <- c("A","B","C","D","E","F","G","H","I","L")
DF <- data.frame(species, obs_2010, obs_2014, stringsAsFactors=T)

我绘制了 2010 年值与 2014 年值的图,并得到了相关图。 https://i.stack.imgur.com/W8fM3.jpg

其中一些物种是姐妹物种(例如 A-L、B-I、G-H)。 除了基于所有 10 个物种的回归线之外,我还想在点 A 和 L 之间画一条线,在 B 和 I 之间画一条线,在 G 和 H 之间画另一条线。 基本上,我想得到这个图(现在用 Paint 制作;)) https://i.stack.imgur.com/9uXEQ.png

这里是我所做的一些不成功的尝试:

#pairs to connect: A-L, B-I, G-H
sister=c(1,2,NA,NA,NA,NA,3,3,2,1)

sistasp <- data.frame(species=DF$species,sister=sister, stringsAsFactors=T)

#trial1
ggplot(DF, aes(x=obs_2010, y=obs_2014)) + 
  geom_point(aes(col=species), shape=16, size=3) + theme_bw() + xlim(0,20) + ylim(0,20) +
  geom_smooth(method=glm, se=F, col="black") +   
  geom_line(aes(group=sister), na.rm=T)
#almost good, but also points with NA (those without sister species) are connected

#trial2
ggplot(DF, aes(x=obs_2010, y=obs_2014)) + 
  geom_point(aes(col=species), shape=16, size=3) + theme_bw() + xlim(0,20) + ylim(0,20) +
  geom_smooth(method=glm, se=F, col="black") +  
  geom_segment(data = merge(DF, sistasp, by = "sister"), 
             aes(x=y2010.x, xend=y2010.y, y=y2014.x, yend=y2014.y))
#error message Error in FUN(X[[i]], ...) : object 'y2010.x' not found

谢谢您的帮助=)

r ggplot2 line
1个回答
0
投票

所以我认为您的第一种方法几乎是正确的,但您可能希望将传递给

geom_line()
的数据子集为仅具有姐妹信息的数据。我将
$sister
添加到
DF
,以便分组与数据一致。

DF$sister <- sister

ggplot(DF, aes(x=obs_2010, y=obs_2014)) + 
  geom_point(aes(col=species), shape=16, size=3) + theme_bw() + xlim(0,20) + ylim(0,20) +
  geom_smooth(method=glm, se=F, col="black") +   
  geom_line(data = DF[!is.na(sister),], aes(group=sister), na.rm=T)

这能给你你想要的吗?

© www.soinside.com 2019 - 2024. All rights reserved.