如何在R中构建按年份区分主/子版块的特定排名关联图表?
解决方案:用ggplot绘制问卷版块演变图表
核心思路
- 将年份(
year)作为X轴基础,通过偏移量区分主/子版块的左右展示区域 - 用
id映射颜色实现同主题版块的颜色统一,用name作为标签展示名称变化 - 把因子型的
rank转为数值型,确保Y轴符合问卷实际排序
代码实现
1. 加载所需包
library(ggplot2) library(dplyr)
2. 数据预处理
先转换rank为数值型,同时为每个年份的主/子版块添加X轴偏移量:
# 读取示例数据(替换为你的完整数据集) df <- structure(list(rank = structure(1:15, levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75"), class = "factor"), year = c("1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986", "1986"), name = c("SectionA", "SectionB", "SectionC", "SectionD", "SectionE", "SectionF", "SectionG", "SectionH", "SectionI", "SectionJ", "SectionK", "SectionL", "SectionM", "SectionN", "SectionO"), section = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L), levels = c("0", "1"), class = "factor"), id = c("ID1", "ID1", "ID2", "ID3", "ID4", "ID5", "ID6", "ID7", "ID8", "ID9", "ID10", "ID11", "ID12", "ID13", "ID14")), row.names = c(NA, -15L), class = c("tbl_df", "tbl", "data.frame")) # 数据处理 df_processed <- df %>% mutate( rank_num = as.numeric(as.character(rank)), # 转换rank为数值,保证排序正确 year_num = as.numeric(year), # 转换year为数值用于计算偏移 x_pos = case_when( section == "0" ~ year_num - 0.2, # 主版块左移,占据年份左侧区域 section == "1" ~ year_num + 0.2 # 子版块右移,占据年份右侧区域 ) )
3. 绘制图表
ggplot(df_processed, aes(x = x_pos, y = rank_num, color = id)) + # 用点标记每个版块的位置,大小可按需调整 geom_point(size = 4) + # 添加版块名称标签,避免重叠可调整vjust/hjust参数 geom_text(aes(label = name), hjust = 0.5, vjust = -0.8, size = 3) + # 设置X轴刻度为原始年份,对齐到区域中间 scale_x_continuous( breaks = unique(df_processed$year_num), labels = unique(df_processed$year) ) + # 设置Y轴为rank数值,保留问卷原始顺序 scale_y_continuous(breaks = unique(df_processed$rank_num)) + # 添加年份分隔虚线,增强区域区分度 geom_vline( xintercept = unique(df_processed$year_num), linetype = "dashed", color = "gray50" ) + # 自定义图表标签 labs( x = "年份", y = "问卷版块排名", color = "主题ID" ) + # 调整主题样式,优化可读性 theme_minimal() + theme( axis.text.y = element_text(size = 8), legend.position = "bottom" )
关键细节说明
- X轴偏移:
-0.2和+0.2的偏移量可根据需求调整,确保同一年份的主/子版块区域不重叠 - 颜色映射:以
id作为颜色变量,自动为同一主题的版块分配相同颜色,即使名称(name)变化也能保持视觉统一 - 标签展示:
geom_text直接显示版块名称,清晰体现跨年份的更名情况 - 分隔线:
geom_vline添加年份分隔虚线,帮助区分不同年份的版块分布
内容的提问来源于stack exchange,提问作者Val
相关产品推荐
相关产品推荐

