在R中添加线对

Bas*_*sen 4 r scatter-plot

我有一些成对测量的数据(例如 1C,1M,2C和2M),我分别绘制了这些数据(如C和M)。但是,我想在每对之间添加一条线(例如,从C列的点1到M'列'的点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
Run Code Online (Sandbox Code Playgroud)

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

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

当前情节: 在此处输入图片说明

我想知道实现此目标需要什么命令或功能(下面仅给出了一些代码,给出了所需结果的粗略草图)。

所需图 在此处输入图片说明

另外,用ggplot进行此操作对我也很好,我可以使用以下替代ggplot代码来生成类似于上述第一个图的图:

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

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

Jas*_*lns 5

我可能会建议将其分解为多个可视化文件-拥有更多数据,我觉得这种类型的绘图将变得难以解释。另外,我不确定是否可以绘制geom_lines并将其与的附加调用关联geom_jitter。话虽如此,这可以带给您大部分的帮助:

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

情节

诀窍是group在内部geom_line()而不是在内部指定您的美感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")
Run Code Online (Sandbox Code Playgroud)

Cowplot网格