在R中如何绘制参与者双调查得分的扁平斜率散点图?
两次调查得分变化的可视化方案(R实现)
推荐图表类型
- 有序斜率图(Ordered Slope Graph):将参与者按得分变化幅度(Survey2 - Survey1)排序后绘制斜率图,避免线条交叉杂乱,既能展示个体得分变化,也能直观看到整体趋势。
- 横向差值连线图:以得分为横轴、按差值排序的参与者为纵轴,用线段连接同一参与者的两次得分,清晰呈现每个个体的变化方向与幅度。
R实现步骤(以有序斜率图为例)
1. 加载所需包
library(tidyverse)
2. 准备示例数据
df <- tibble( participantNum = 1:6, survey1_score = c(-28, -14, 20, 6, -20, 22), survey2_score = c(4, 16, -10, 8, 26, 24) )
3. 数据预处理
将宽格式转长格式,计算得分差值并按差值排序参与者:
df_processed <- df %>% mutate(score_diff = survey2_score - survey1_score) %>% arrange(score_diff) %>% mutate(participant_order = factor(participantNum, levels = participantNum)) %>% pivot_longer( cols = starts_with("survey"), names_to = "survey", values_to = "score", names_prefix = "survey" ) %>% mutate(survey = factor(survey, levels = c("1", "2")))
4. 绘制有序斜率图
ggplot(df_processed, aes(x = survey, y = score, group = participant_order)) + geom_line(aes(color = score_diff), alpha = 0.7, linewidth = 1) + geom_point(size = 3) + geom_text(aes(label = participantNum), vjust = -1, size = 3) + scale_color_gradient2(low = "blue", mid = "gray", high = "red", midpoint = 0) + labs(x = "调查轮次", y = "得分", color = "得分变化(Survey2 - Survey1)") + theme_minimal() + theme(axis.text.y = element_blank(), panel.grid.major.y = element_blank())
可选方案:横向差值连线图
更聚焦个体变化的横向对比:
df_diff <- df %>% mutate(score_diff = survey2_score - survey1_score) %>% arrange(score_diff) %>% mutate(participant_order = factor(participantNum, levels = participantNum)) ggplot(df_diff) + geom_segment( aes(x = survey1_score, xend = survey2_score, y = participant_order, yend = participant_order, color = score_diff), linewidth = 1 ) + geom_point(aes(x = survey1_score, y = participant_order), size = 3, color = "darkblue") + geom_point(aes(x = survey2_score, y = participant_order), size = 3, color = "darkred") + scale_color_gradient2(low = "blue", mid = "gray", high = "red", midpoint = 0) + labs( x = "得分", y = "参与者(按得分变化排序)", color = "得分变化(Survey2 - Survey1)", title = "两次调查得分变化对比" ) + theme_minimal()
内容的提问来源于stack exchange,提问作者fourteen14
相关产品推荐
相关产品推荐

