如何在ggplot2中手动添加图例且不覆盖已有图例
解决方案
要给你的图添加指定的超平面图例,核心是让超平面的颜色映射到美学属性(而非直接指定颜色),同时避免和散点的颜色映射冲突。这里用ggnewscale包来实现独立的多图例,具体代码如下:
# 若未安装ggnewscale,先执行安装 # install.packages("ggnewscale") library(ggplot2) library(ggnewscale) # 生成原始数据 x1 <- rnorm(200) x2 <- rnorm(200, 2, 1) y <- ifelse(1 + 3*x1 - x2 > 0, "1 + 3*x1 - x2 > 0", "1 + 3*x1 - x2 < 0") z <- ifelse(-2 + x1 + 2*x2 > 0, "-2 + x1 + 2*x2 > 0", "-2 + x1 + 2*x2 < 0") dat <- data.frame(x1, x2, y, z) # 整理超平面参数,方便批量绘制和映射 hyperplanes <- data.frame( intercept = c(1, 1), slope = c(3, -0.5), label = c("1 + 3*x1 - x2 = 0", "-2 + x1 + 2*x2 = 0"), line_color = c("red", "green") ) # 绘图 ggplot(dat, aes(x1, x2)) + # 绘制散点,映射颜色到分类y、形状到区域z geom_point(aes(color = y, shape = z)) + # 设置散点的颜色图例标题 scale_color_discrete(name = "Class") + # 设置形状图例标题 scale_shape_discrete(name = "Region") + # 开启新的颜色比例尺通道,避免和散点的颜色映射冲突 new_scale_color() + # 绘制超平面,将颜色映射到超平面标签(用于生成图例) geom_abline( data = hyperplanes, aes(intercept = intercept, slope = slope, color = label), size = 1.5 ) + # 指定超平面的颜色对应关系,设置图例标题 scale_color_manual( name = "Hyperplanes", values = setNames(hyperplanes$line_color, hyperplanes$label) ) + # 调整图例位置到底部,优化布局 theme( legend.position = "bottom", legend.box = "vertical", legend.margin = margin(t = 10) )
关键改动说明:
- 用
ggnewscale的new_scale_color()创建独立的颜色映射通道,让散点和超平面的颜色图例互不干扰 - 将超平面参数整理为数据框,通过映射
color = label自动生成图例项 - 用
scale_color_manual指定超平面的颜色和图例标题 - 通过
theme(legend.position = "bottom")将所有图例移至图的底部
内容的提问来源于stack exchange,提问作者Sandy Vo
相关产品推荐
相关产品推荐

