[英]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
,因此它仍然是长格式数据中的一列,然后将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()
自定义图例标题、标签和 colors。
不是对您的问题的直接回答,而是对(可能)更引人注目的可视化的建议。 您正在处理成对的数据,因此将其分为两个维度。 散点图 plot 非常适合此目的。 您的数据已经处于正确的形状,您可以添加一条等号线以使比较更容易。
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)
由代表 package (v2.0.1) 于 2021 年 12 月 20 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.