如何在ggplot2箱线图上添加单个受试者的得分连线?
在ggplot2箱线图上叠加特定个体的得分连线
问题背景
数据集包含数百条观测,结构如下:
| Y-AXIS | X-AXIS | SUBJECT |
|---|---|---|
| 2.2796598 | F1 | 1 |
| 0.9118639 | F1 | 2 |
| 2.7111228 | F3 | 3 |
| 2.7111228 | F2 | 4 |
| 2.2796598 | F4 | 5 |
| 2.3876401 | F10 | 6 |
| ... | ... | ... |
其中:
X-AXIS是大于0的连续值(通常小于100)Y-AXIS是包含10个水平的分类变量SUBJECT代表个体,每个个体对应10条观测(每个Y-AXIS水平各一条)
已通过以下代码生成基础箱线图:
plot1 <- ggplot(longdata, aes(x = X_axis, y = Y_axis)) + geom_boxplot() + ylim(0, 12.5) + stat_summary(fun = "mean", geom = "point", shape = 2, size = 3, color = "purple")
需求:在箱线图上叠加某一特定SUBJECT的10个得分连线,并自定义连线的颜色、粗细等样式。
解决方案
1. 筛选目标个体数据
先从原数据集中提取出需要展示的特定个体数据,例如要展示SUBJECT = 1的观测:
target_subject <- subset(longdata, SUBJECT == 1)
2. 叠加个体得分连线与标记点
使用geom_line()连接该个体的所有得分点,同时用geom_point()标记每个数据点。注意必须指定group = SUBJECT,确保ggplot能识别同一个体的所有观测并正确连线:
plot1 + # 添加连线 geom_line(data = target_subject, aes(x = X_axis, y = Y_axis, group = SUBJECT), color = "red", size = 1.2, linetype = "solid") + # 添加数据点 geom_point(data = target_subject, aes(x = X_axis, y = Y_axis), color = "red", size = 4, shape = 19)
3. 叠加多个个体(可选)
如果需要同时展示多个个体的得分趋势,可一次性筛选多个个体,通过color = factor(SUBJECT)区分不同个体:
# 筛选多个目标个体 multi_targets <- subset(longdata, SUBJECT %in% c(1, 2)) plot1 + geom_line(data = multi_targets, aes(x = X_axis, y = Y_axis, group = SUBJECT, color = factor(SUBJECT)), size = 1) + geom_point(data = multi_targets, aes(x = X_axis, y = Y_axis, color = factor(SUBJECT)), size = 3) + # 自定义个体颜色 scale_color_manual(values = c("darkblue", "forestgreen"))
4. 样式自定义参数说明
- 连线样式:
color:设置连线颜色(支持颜色名称、十六进制码)size:控制连线粗细(数值越大越粗)linetype:设置线型,可选值如"solid"实线、"dashed"虚线、"dotted"点线
- 数据点样式:
shape:控制点的形状(19为实心圆,2为空心三角,1为空心圆等)size:控制点的大小fill:针对带填充的形状(如shape=21),设置填充颜色
示例:设置橙色虚线连线+空心点
geom_line(data = target_subject, aes(x = X_axis, y = Y_axis, group = SUBJECT), color = "#FF7F00", size = 1, linetype = "dashed") + geom_point(data = target_subject, aes(x = X_axis, y = Y_axis), shape = 21, fill = "white", color = "#FF7F00", size = 3)
内容的提问来源于stack exchange,提问作者Adriaan Spruyt
相关产品推荐
相关产品推荐

