如何在ggplot的散点图中绘制配对数据?

How to plot paired data in a scatter plot in ggplot?

我有一个数据框,其中包含来自同一主题的不同时间点(“时间 0”和“时间 3”)的配对样本。如何为每个主题生成 x 坐标对应“时间 0”、y 坐标对应“时间 3”的散点图。

subject = c(1,1,2,2,3,3)
time = c(0,3,0,3,0,3)
dependent_variable = c(1,5,4,12,3,9)
df = data.frame(subject, time, dependent_variable)

为了达到您想要的结果,您可以使用例如重塑数据tidy::pivot_wider:

subject = c(1,1,2,2,3,3)
time = c(0,3,0,3,0,3)
dependent_variable = c(1,5,4,12,3,9)
df = data.frame(subject, time, dependent_variable)

library(ggplot2)
library(tidyr)

df_wide <- df %>% 
  pivot_wider(names_from = time, values_from = dependent_variable, names_prefix = "time")

ggplot(df_wide, aes(time0, time3, color = factor(subject))) +
  geom_point()