在 R 中添加对线

Add pair lines in R

我有一些成对测量的数据(例如 1C、1M、2C 和 2M),我分别绘制了这些数据(作为 C 和 M)。但是,我想在每对之间添加一条线(例如 从 C 列中的点 1 到 M 'column' 中的点 1 的线)。

整个数据集的一小部分:

PairNumber  Type    M
1   M   0.117133
2   M   0.054298837
3   M   0.039734
4   M   0.069247069
5   M   0.043053957
1   C   0.051086898
2   C   0.075519
3   C   0.065834198
4   C   0.084632915
5   C   0.054254946

我使用以下微小的 R 代码片段生成了下图:

boxplot(test$M ~ test$Type)
stripchart(test$M ~ test$Type, vertical = TRUE, method="jitter", add = TRUE, col = 'blue')

当前剧情:

我想知道我需要什么命令或什么功能来实现这个(下面给出了所需结果的粗略草图,只有一些行)。

想要的情节:

或者,用 ggplot 做这个对我来说也很好,我有以下替代 ggplot 代码来生成类似于上面第一个的图:

ggplot(,aes(x=test$Type, y=test$M)) + 
  geom_boxplot(outlier.shape=NA) +
  geom_jitter(position=position_jitter(width=.1, height=0))

我一直在尝试 geom_path,但我没有找到正确的语法来实现我想要的。

我可能会建议将其分解为多个可视化——如果数据更多,我觉得这种类型的图会变得难以解释。此外,我不确定是否可以绘制 geom_lines 并将它们与对 geom_jitter 的附加调用连接起来。话虽这么说,这让你完成了大部分工作:

ggplot(df, aes(x = Type, y = M)) +
  geom_boxplot(outlier.shape = NA) +
  geom_line(aes(group = PairNumber)) +
  geom_point()

诀窍是在 geom_line() 内指定您的 group 美学,而不是在 ggplot() 内指定您的审美。

附加说明:没有理由在 ggplot() 内完全限定您的美学变量——也就是说,没有理由这样做 ggplot(data = test, aes(x = test$Type, y = test$M);相反,只需使用:ggplot(data = test, aes(x = Type, y = M)).


更新
利用 cowplot 在不同的图中可视化此数据可能会有所帮助:

library(cowplot)

p1 <- ggplot(df, aes(x = Type, y = M, color = Type)) +
  geom_boxplot()

p2 <- ggplot(df, aes(x = Type, y = M, color = Type)) +
  geom_jitter(position = position_jitter(width = 0.1, height = 0))

p3 <- ggplot(df, aes(x = M, color = Type, fill = Type)) +
  geom_density(alpha = 0.5)

p4 <- ggplot(df, aes(x = Type, y = M)) +
  geom_line(aes(group = PairNumber, color = factor(PairNumber)))

plot_grid(p1, p2, p3, p4, labels = c(LETTERS[1:4]), align = "v")