简体   繁体   English

用R中的ggplot2中的线连接来自两个数据集的点

[英]Connecting points from two datasets with lines in ggplot2 in R

I want to connect datapoints from two datasets with a vertical line. 我想用垂直线连接来自两个数据集的数据点。 The points that should be connected vertically have the same identifier (V), but I was hoping to keep the datasets separate. 应该垂直连接的点具有相同的标识符(V),但我希望将数据集分开。

Here is my figure so far: 到目前为止,这是我的身材:

d1 <- data.frame (V = c("A", "B", "C", "D", "E",  "F", "G", "H"), 
                  O = c(9,2.5,7,8,7,6,7,7.5), 
                  S = c(6,5,3,5,3,4,5,6))

d2 <- data.frame (V = c("A", "B", "C", "D"), 
              O = c(10,3,7.5,8.2), 
              S = c(6,5,3,5))

scaleFUN <- function(x) sprintf("%.0f", x)
p<-ggplot(data=d1, aes(x=S, y=O), group=factor(V), shape=V) +
 geom_point(size = 5, aes(fill=V),pch=21, alpha = 0.35)+
 theme_bw()+
geom_point(data = d2, size=5, aes(fill=V), pch=22,colour="black")+
theme(legend.title=element_blank())+
xlab(expression(italic("S"))) + theme(text = element_text(size=25))+
ylab(expression(italic("O")))+ theme(text = element_text(size=25))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
theme(axis.text.y=element_text(angle=90, hjust=1))+
theme(legend.position="none") # remove legend

print(p)

So the final figure would look something like this: 因此,最终数字将如下所示: 数字 Can I do this with geom_line() without combining datasets (so the other formatting can be separate for each dataset)? 是否可以在不合并数据集的情况下使用geom_line()做到这一点(因此每个数据集的其他格式可以分开)?

As bouncyball pointed out, you can use a separate data set ( merge d from d1 and d2 ) with geom_segment . 正如bouncyball指出的那样,您可以将单独的数据集( d1d2 d merge )与geom_segment一起geom_segment

See the following: 请参阅以下内容:

ggplot(data = d1, aes(x = S, y = O), group = factor(V), shape = V) +
  geom_point(size = 5, aes(fill = V), pch = 21, alpha = 0.35) +
  geom_point(data = d2, size = 5, aes(fill = V), pch = 22, colour = "black") +
  geom_segment(data = merge(d1, d2, by = 'V'), 
               aes(x = S.x, xend = S.y, y = O.x, yend = O.y)) +
  guides(fill = FALSE)

Which yields: 产生:

在此处输入图片说明

You can add your themes also. 您也可以添加主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM