首页 > 解决方案 > 使用 ggplot2 中的 geom_segment() 连接多个时间点

问题描述

我有一个看起来像这样的 data.frame

tree=data.frame(time=c(0,0,0,1,1,1,2,2,2), pop.size=c(10,10,10,14,13,10,17,24,13), 
                parents=c(NA,NA,NA,1,2,3,1,2,3), offspring=c(1,2,3,1,2,4,5,6,7))

我想在每个时间点将后代绘制为带有 geom_point 的点,并使用 geom_segment() 或任何其他可能有用的几何图形将它们与上一个时间点的父母联系起来。

ggplot(tree,aes(x=time, y=offspring))+
  geom_point() +
  theme_bw()

在此处输入图像描述

任何帮助,将不胜感激。虽然我可以将时间点 1 和时间点 2 连接起来,但很难将时间点 2 和时间点 3 连接起来。我不得不告诉你,我最多有 100 个点

编辑:我想看到这样的东西。在这里,我仅将时间点 1 的元素与时间点 2 的元素连接起来。我想将时间点 2 与时间点 3 连接起来,我的情节看起来像一棵家谱树

ggplot(tree,aes(x=time, y=offspring))+
  geom_point() +
  theme_bw() +
  geom_segment(aes(x=time[1], xend=time[5], y=parents, yend=offspring))

在此处输入图像描述

标签: rggplot2geom-curve

解决方案


你可以试试:

ggplot(tree,aes(x=time, y=offspring,group=time))+geom_line()+
    geom_point() +
    theme_bw()

在此处输入图像描述

或者:

ggplot(tree,aes(x=time, y=offspring,group=1))+geom_line()+
    geom_point() +
    theme_bw()

在此处输入图像描述

更新

试试这个代码:

tree %>% group_by(time) %>% mutate(ind = 1:length(time)) -> tree2
ggplot(tree2,aes(x=time, y=offspring,group=ind))+geom_line()+
  geom_point() +
  theme_bw()

在此处输入图像描述


推荐阅读