2017-09-24 84 views
-2

我有三列:“原始”,“pos1”,“pos2”。每一行都是一个人。我想创建一个散点图,其中“原始”位于x轴上,pos1和pos2值位于y轴上。所以每个原稿都会有一个pos1点和一个pos2点。我可以创建两种不同的颜色来区分pos1和pos2点。但是我想要的是为每个人在pos1和pos2之间添加一行。如果我有100个人,则会有100条短线,连接每个pos1和pos2。有没有什么办法可以在ggplot中做到这一点?连接r中每一行的每列ggplot2散点图

谢谢!

回答

2

听起来就像你正在寻找geom_segment。像下面的内容可以工作:

library(ggplot2) 

ggplot(df, aes(x = original)) + 
    geom_point(aes(y = pos1, col = "pos1")) + 
    geom_point(aes(y = pos2, col = "pos2")) + 
    geom_segment(aes(xend = original, 
        y = pos1, yend = pos2)) + 
    ylab("positions") + 
    scale_colour_manual(name = "Position", 
         values = c(pos1 = "red", 
           pos2 = "blue")) 

enter image description here

数据:

set.seed(1) 
df <- data.frame(
    original = 1:100, 
    pos1 = rnorm(100), 
    pos2 = rnorm(100, mean = 5) 
) 

如果不为你工作,你分享你的实际数据的样本。

+0

谢谢,林。这正是我所期待的!非常感谢! –