r - 按类别创建散点图,其中线条连接来自 ggplot 中相同 ID 的值

标签 r ggplot2

我正在尝试基于两个类别创建一个散点图,并通过一条线连接具有相同 ID 的任何点。我创建了一个示例数据集。我希望天数作为 x 轴,分数作为 y 轴,并且每个值研究的颜色都不同。我可以在 ggplot 中做到这一点,正如我所展示的,但我无法弄清楚如何连接来自同一 ID 的点。

library(ggplot2)
Id <- c(1,2,3,4,1,3)
Score <- c(24,27,17,25,28,24)
Study <- c(1,1,1,2,2,2)
days <- c(8,17,42,36,69,80)

X <- as.data.frame(cbind(Id, Score, Study, days ))

ggplot(X, aes(days, Score)) + 
geom_jitter(width = 0.3, height = 0.3, aes(colour = as.factor(Study))) +
geom_segment(aes(x=42, y=17, xend=80, yend=24), lty=2, colour="purple") +
geom_segment(aes(x=8, y=24, xend=69, yend=28), lty=2, colour="purple") 

enter image description here

例如,我希望 ID 1 的值 24 和 28 之间以及 ID 3 的值 17 到 24 之间有一条线。我用 geom_segment 添加了这些,但在实际数据集中,我正在使用它们将有数百个连接。感谢您的帮助,谢谢!

最佳答案

使用 group审美的:

ggplot(X, aes(days, Score)) +
    geom_jitter(width = 0.3, height = 0.3, aes(colour = as.factor(Study))) +
    geom_line(aes(group = Id), lty = 2, colour = "purple")

来自 ?geom_line的描述:

The group aesthetic determines which cases are connected together.

关于r - 按类别创建散点图,其中线条连接来自 ggplot 中相同 ID 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42101505/

相关文章:

r - 制作线性模型时因子与矢量对象类型的影响

r - 如何用连字符分隔列

r - 解释一下ggplot2警告: "Removed k rows containing missing values"

r - 设置多面图中的列(或行)数

r - 在ggplot2中使用geom_violin将统计信息传递给geoms

R - ggplot geom_dotplot 形状选项

r - 在 data.frame 的 ggplot 图例中添加信息

r - 在 tibble 中添加具有可变列名称的列

r - R 中的嵌套 Logit 或 Probit

r - 基于边权重的子图