如何解决ggplot2中多geom_point图层图例重叠及Faits点样式问题
ggplot2 双散点图层图例修复方案
问题解决思路
你的问题核心在于两个geom_point图层同时生成图例导致重叠,且区域汇总点未关联尺寸美学导致图例显示异常。以下是针对性修复:
- 关闭区域点的自动图例,让主数据点(Faits)负责输出color和size图例
- 手动自定义color图例,明确区分主数据点(空心圆)和区域汇总点(实心圆)
- 固化两类点的形状属性,确保显示符合预期
修改后的完整代码
library(ggplot2) library(ggrepel) library(stringr) set.seed(123) data_filtered <- data.frame( evolution = runif(15, -10, 10), tauxpourmille = runif(15, 0, 100), faits = sample(1:100, 15, replace = TRUE), Code.région = sample(letters[1:3], 15, replace = TRUE), Code.département = sample(LETTERS[1:5], 15, replace = TRUE) ) evol_tpm_reg_filtered <- data.frame( evolution_reg = runif(3, -10, 10), tauxpourmille = runif(3, 0, 100), Code.région = letters[1:3] ) x_label <- "Évolution" y_label <- "Taux pour mille" region_colors <- c("red", "blue", "green") ggplot(data_filtered, aes(x = evolution, y = tauxpourmille, size = faits, color = factor(Code.région))) + # 主数据点:空心圆,负责输出图例 geom_point(shape = 1, stroke = 1.3, alpha = 0.6, show.legend = TRUE) + geom_text_repel(aes(label = Code.département), family = "sans", box.padding = 3, size = 5, min.segment.length = 0, force = 20, max.overlaps = 50, segment.size = 0.5, show.legend = FALSE) + # 区域汇总点:实心圆,关闭自动图例 geom_point(data = evol_tpm_reg_filtered, aes(x = evolution_reg, y = tauxpourmille, color = factor(Code.région)), size = 5, shape = 16, show.legend = FALSE) + labs(x = str_wrap(x_label, width = 90), y = str_wrap(y_label, width = 35), color = "Region", size = "Faits") + theme_minimal() + scale_color_manual(values = region_colors) + scale_size_area(max_size = 30, breaks = c(min(data_filtered$faits), median(data_filtered$faits), max(data_filtered$faits)), labels = scales::number_format(accuracy = 1)) + # 自定义color图例:明确区分两类点 guides( color = guide_legend( override.aes = list( shape = c(1, 1, 1), # 图例中主数据点固定为空心圆 size = c(5,5,5) # 统一图例点大小,不受size美学影响 ), title = "Region\n(Faits: 空心圆 | 区域汇总: 实心圆)" ), size = guide_legend(title = "Faits") ) + theme(axis.title.x = element_text(family = "sans", margin = margin(t = 15)), axis.title.y = element_text(family = "sans", margin = margin(r = 15)), axis.text.x = element_text(face = "bold", family = "sans"), axis.text.y = element_text(face = "bold", family = "sans"), axis.line.x = element_line(size = 1, color = "lightgray"), axis.line.y = element_line(size = 1, color = "lightgray"), legend.position = "right") + expand_limits(x = range(data_filtered$evolution) + c(-0.5, 0.5) * diff(range(data_filtered$evolution)), y = range(data_filtered$tauxpourmille) + c(-0.5, 0.5) * diff(range(data_filtered$tauxpourmille)))
关键修改说明
- 关闭区域点图例:将区域汇总点图层的
show.legend设为FALSE,避免重复生成图例元素造成重叠 - 自定义颜色图例:通过
guide_legend()强制图例中的主数据点显示为空心圆,并在标题中补充两类点的区分说明 - 固化点形状:主数据点保持
shape=1(空心圆),区域点保持shape=16(实心圆),确保视觉效果符合需求
内容的提问来源于stack exchange,提问作者NoNameBoyy
相关产品推荐
相关产品推荐

