如何在 R 中的箱线图中连接点的连接线中添加组

How to add groups in connecting lines connecting dots in boxplots in R

我制作了以下数据集:

before <- c(100, 120, 140, 130, 120, 100, 100)  
after <- c(140, 100, 160, 120, 90, 70, 70)  
pain_group <- c(1, 0, 1, 0, 0, 0, 0)  
d <- data.frame(before=before, after=after, pain_group=pain_group)

d$id <- 1:nrow(d)
d <- tidyr::gather(d, Measurement, quantity, -id)

我用单独的点和连接线在箱线图中绘制了数据:

ggplot(d2, aes(Measurement, quantity_cluster2)) + 
  geom_boxplot() +  
  geom_point() +
  geom_line(aes(group = id), color = 'grey') +
  scale_x_discrete(limits = c('before', 'after'))

但是我希望 pain_group 用不同颜色的线(和点)分隔。我怎样才能做到这一点?

提前致谢!

您需要从 gather 中排除 pain_group,这样它仍然是 long-form 数据中的一列,然后将 color = factor(pain_group) 添加到 aes()

d2 <- tidyr::gather(d, Measurement, quantity, -id, -pain_group)

ggplot(d2, aes(Measurement, quantity)) + 
  geom_boxplot() +  
  geom_point(aes(color = factor(pain_group))) +
  geom_line(aes(group = id, color = factor(pain_group))) +
  scale_x_discrete(limits = c('before', 'after'))

您可以使用 labs() 自定义图例标题,或者使用 scale_color_continuous() 自定义图例标题、标签和颜色。

不是对您问题的直接回答,而是对(可能)更具吸引力的可视化的建议。您正在处理成对数据,因此将其分为两个维度。散点图非常适合该目的。你的数据已经是正确的形状了,你可以添加一条等号线来让比较更容易。

library(ggplot2)
before <- c(100, 120, 140, 130, 120, 100, 100)  
after <- c(140, 100, 160, 120, 90, 70, 70)  
pain_group <- c(1, 0, 1, 0, 0, 0, 0)  
d <- data.frame(before=before, after=after, pain_group=pain_group)

lims <- range(c(before, after))

ggplot(d) +
  geom_point(aes(before, after, color = as.character(pain_group))) +
  geom_abline(intercept = 0, slope = 1) +
  coord_cartesian(xlim = lims, ylim = lims)

reprex package (v2.0.1)

于 2021-12-20 创建