在小提琴图的填充条件下将散点与线配对

Pairing Scatter Points with Lines Across Fill Condition of Violin Plot

这里是一个 data.frame 三主题的 2 x 2 设计:

x<-data.frame("sub" = rep(c("sub1","sub2","sub3"),times=4),
          "cond1" = rep(c("A","B"),times=c(6,6)),
          "cond2" = rep(c("C","C","C","D","D","D"),times=2),
          "score" = c(6,5,4, 5,4,3, 4,3,2, 3,2,1))

这里是分割小提琴图(函数,https://gist.github.com/Karel-Kroeze/746685f5613e01ba820a31e57f87ec87):

dodge <- position_dodge(width=.5)
ggplot(x, aes(x=cond1, y=score, fill=cond2))+
  geom_split_violin(trim = F)+
  geom_point(shape=16,position=dodge)

我想要做的是将各个主题散点与一条横跨填充条件的线连接起来(例如,cond1 A 和 cond2 C 中的 sub1 将连接到 cond1 A 和 cond2 D 中的 sub1)。有谁知道这是否可能?

这是一种方法。首先,我 spread table 所以 geom_segment 的开头和结尾可以基于不同的列。然后我将 cond1 值转换为数字(这是 ggplot 在幕后所做的)并将它们输入 x 字段。 0.12 的 x 闪避偏移是手动的,但可能有一种聪明的方法(超出我目前的理解)使用 ggplot 设置自动确定它。

library(tidyverse)
dodge <- position_dodge(width=.5)
ggplot(x, aes(x=cond1, y=score, fill=cond2))+
  geom_split_violin(trim = F)+
  geom_point(shape=16,position=dodge) +
  geom_segment(data = x %>% spread(cond2, score),
               aes(x    = as.numeric(cond1) - 0.12, 
                   xend = as.numeric(cond1) + 0.12,
                   y = C, yend = D), inherit.aes = FALSE, color = "black")