如何在R中绘制对称的两组排名对比图
R语言对称排名对比图实现方案
你之前使用GGally::ggparcoord无法实现两侧各自排序的对称斜坡图效果,是因为ggparcoord默认共用统一y轴刻度,不能分别对左右两列排名做独立排序,以下是可直接运行的实现代码:
1. 加载依赖包
library(tidyverse) library(hrbrthemes) library(viridis)
2. 构造示例数据集
data <- data.frame( Group = letters[1:10], Ranking1 = 1:10, Ranking2 = c(1,4,2,3,7,5,9,11,6,16), Pop = c(12345,127868,123477,9485,132588,38741,8372,53423,238419,31314) )
3. 数据预处理
把宽表转为长表,同时计算左右两侧的独立y轴位置(确保排名1在最上方,两侧各自按对应排名排序):
plot_data <- data %>% pivot_longer(cols = c(Ranking1, Ranking2), names_to = "Rank_type", values_to = "Rank_val") %>% mutate( x_pos = ifelse(Rank_type == "Ranking1", 1, 2), y_pos = ifelse(Rank_type == "Ranking1", -Ranking1, -Ranking2) )
4. 绘制对称排名对比图
ggplot(plot_data, aes(x = x_pos, y = y_pos, group = Group, color = Group)) + # 中间连线 geom_line(alpha = 0.7, linewidth = 1) + # 散点,大小映射人口数值 geom_point(aes(size = Pop), alpha = 0.8) + # 左侧标注:组名+Ranking1数值 geom_text(data = filter(plot_data, Rank_type == "Ranking1"), aes(x = 0.9, label = paste0(Group, " (", Rank_val, ")")), hjust = 1, size = 3.5) + # 右侧标注:组名+Ranking2数值 geom_text(data = filter(plot_data, Rank_type == "Ranking2"), aes(x = 2.1, label = paste0(Group, " (", Rank_val, ")")), hjust = 0, size = 3.5) + # 两侧表头 annotate("text", x = 1, y = 0, label = "Ranking1", size = 5, fontface = "bold") + annotate("text", x = 2, y = 0, label = "Ranking2", size = 5, fontface = "bold") + # 颜色和主题设置 scale_color_viridis(discrete = TRUE) + scale_size_continuous(range = c(2, 8)) + theme_ipsum() + theme_void() + theme( legend.position = "none", plot.title = element_text(hjust = 0.5, size = 16) ) + # 调整x轴范围留出标注空间 xlim(0.5, 2.5) + labs(title = "Ranking")
上述代码生成的图表两侧会分别按Ranking1、Ranking2的排名从上到下排列,中间用连线连接同一组的两个排名位置,完全匹配你需要的对称样式。你可以根据需求调整文本大小、点的大小范围、颜色映射规则等参数。
内容的提问来源于stack exchange,提问作者pepi.guerra
相关产品推荐
相关产品推荐

