r - 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))
这产生了这个图形:
到目前为止,一切都很好。现在,当我尝试根据需要连接线路时:
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 使用相同的数据集。在这里,它们是不同的数据集。
解决方案
好的,我应该在发帖前等待五分钟。我想到了:
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
函数的帖子,但我正在考虑在两个数据集之间混合变量;我不认为第二个数据集有相同的变量。
希望这对将来一些疲惫的旅行者有所帮助!
推荐阅读
- bootstrap-4 - SASS - Bootstrap 4 - 尝试使用“按钮大小”混合时出错
- android - 构建 apk 中缺少 Expo manifest.android.config
- powershell - 如何在过程中锁定文件并在使用完PowerShell后解锁?
- java - 在父级中使用子变量。爪哇
- python - 在 Tick Tick 上使用美丽的汤 4 登录
- gitlab - Gitlab Pipelines 电子邮件集成
- laravel - 机器人框架 - Oauth BadRequest - https://token.botframework.com/.auth/web/redirect
- python - 使用 python 打开数据库文件 (.db)
- amazon-web-services - Amazon Linux 2 实例不会出现在 Systems Manager 中
- node.js - 从文件加载 100 万条记录并保存到 PSQL 数据库