首页 > 解决方案 > ggplot2:连接来自不同数据集的点之间的线

问题描述

这是我遇到的问题的一些示例代码:

set.seed(1)
group1 <- sample(c(1, 0), size=200, replace=T)
group2 <- sample(c(1, 0), size=200, replace=T)
score <- rnorm(200) + .5*group1 + 2.2*group2 - 1.7*group1*group2
d <- data.frame(score=score, group1=as.factor(group1), group2=as.factor(group2))
k <- d %>% 
  group_by(group1, group2) %>% 
  summarize(mean=mean(score), median=median(score))
k <- gather(k, "estimate", "value", mean, median)
p <- ggplot(data=d, aes(x=group1, y=score, colour=group2)) + 
    geom_jitter(alpha = .3) +
    geom_point(data=k, aes(y=value, shape=estimate), size=3, position=position_dodge(width=.2))

这产生了这个图形:

ggplot 图像

到目前为止,一切都很好。现在,当我尝试根据需要连接线路时:

p + geom_line(data=k, aes(y=value, linetype=estimate, group=estimate))

我收到一个错误:

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

任何想法为什么会发生这种情况以及如何解决它?

我在网上看到了关于连接它们的其他解决方案,但这些都假设用户对基本 aes 和 geom_line 使用相同的数据集。在这里,它们是不同的数据集。

标签: rggplot2

解决方案


好的,我应该在发帖前等待五分钟。我想到了:

group1 = sample(c(1, 0), size=200, replace=T)
group2 = sample(c(1, 0), size=200, replace=T)
score = rnorm(200) + .5*group1 + 2.2*group2 - 1.7*group1*group2
d = data.frame(score=score, group1=as.factor(group1), group2=as.factor(group2))
k = d%>%group_by(group1, group2)%>%summarize(mean=mean(score), median=median(score))
k = gather(k, "estimate", "value", mean, median)
ggplot(data=d, aes(x=group1, y=score, colour=group2)) + 
    geom_jitter(alpha = .3) +
    geom_point(data=k, aes(y=value, shape=estimate), size=3, position=position_dodge(width=.2)) +
    geom_line(data=k, aes(y=value, linetype=estimate, group=interaction(group2,estimate)), position=position_dodge(width=.2))

产生:

在此处输入图像描述

我看到其他人发布了关于该interaction函数的帖子,但我正在考虑在两个数据集之间混合变量;我不认为第二个数据集有相同的变量。

希望这对将来一些疲惫的旅行者有所帮助!


推荐阅读