我有一个df,其起点是2个组,另一个是终点,是相同的组。我想绘制从第1组开始到满足条件的所有第1组末端,以及从第2组开始到满足条件的所有第2组末端的ggplot画线,但是我不知道我需要什么geom_用于实现这一目标,例如是否可以按照我的尝试从两个不同的数据帧中实现。
# start coordinates:
set.seed(5)
start <- data.frame(matrix(nrow=2,ncol=3))
colnames(start) <- c("group","X","Y")
start$group <- c(1,2)
start$X <- c(5,10)
start$Y <- c(5,10)
# end coordinates:
df <- data.frame(matrix(nrow = 20,ncol=4))
colnames(df) <- c("group","X","Y","condition")
df$group <- rep(c(1,2),each=10)
df$X <- runif(20,0,20)
df$Y <- runif(20,0,20)
df$condition <- c("n","n","n","y","n",
"y","n","n","y","y",
"y","n","n","y","n",
"y","y","y","n","y")
# plot data
library(ggplot2)
ggplot(data=df,aes(x=X,y=Y,color=group))+
geom_point(aes(shape=condition))+
geom_point(data=start,aes(x=X,y=Y),size=2)
我想要的是每组从起点到“ condition = yes”终点的所有行。该图看起来像是两个重叠的星星,但是我无法弄清楚如何在一个geom_命令中从两个数据框调用。这是我到目前为止尝试过的。
ggplot(data=df,aes(x=X,y=Y,color=group))+
geom_point(aes(shape=condition))+
geom_point(data=start,aes(x=X,y=Y),size=2)+
geom_segment(aes(x=start$X,
y=start$Y,
xend=df$X[df$condition=="y"],
yend=df$Y[df$condition=="y"],
group=group))
但这没用。不知道geom_segment是否是我应该使用的。
答案 0 :(得分:1)
merged.data <- merge(x=start, y=df, by="group")
colnames(merged.data) <- c("group", "X.start", "Y.start", "X.end", "Y.end", "condition")
ggplot(df, aes(x=X, y=Y, color=as.character(group))) +
geom_point(size=2) +
geom_point(data=start, aes(x=X, y=Y, color=as.character(group)), size=2) +
geom_segment(data=merged.data[merged.data$condition == "y", ], aes(x=X.start, y=Y.start, xend=X.end, yend=Y.end, color=as.character(group)))
答案 1 :(得分:0)