ggplot2图例优化:调整条纹角度并移除冗余图例项
解决方案
1. 移除冗余图例项
通过填充刻度的limits参数指定需要保留的图例项(A1、A2、A3),搭配breaks和labels对齐,直接过滤掉A4、A5、A6的冗余条目:
# 若使用ggpattern的填充刻度 scale_fill_pattern_discrete( limits = c("A1", "A2", "A3"), breaks = c("A1", "A2", "A3"), labels = c("A1", "A2", "A3") ) # 若用自定义填充色,用scale_fill_manual同理 scale_fill_manual( limits = c("A1", "A2", "A3"), values = c("#FF0000", "#00FF00", "#0000FF"), # 自定义颜色 breaks = c("A1", "A2", "A3"), labels = c("A1", "A2", "A3") )
如果你的等高线是基于连续值分箱生成的,也可以在stat_contour_filled中通过breaks参数控制生成的分组,从源头减少冗余项。
2. 单独调整图例条纹角度
在guides()中使用guide_legend,通过override.aes按图例项顺序指定pattern_angle,顺序要和limits/breaks完全对应:
guides( fill = guide_legend( override.aes = list( pattern_angle = c(45, 135, 0) # 依次对应A1、A2、A3的条纹角度,A3可设为默认0°或自定义值 ) ) )
完整整合示例
假设你的基础绘图代码结构如下,整合后的代码可直接套用:
library(ggplot2) library(ggpattern) # 示例数据(替换为你的实际数据) df <- expand.grid(x = seq(-2, 2, 0.1), y = seq(-2, 2, 0.1)) df$z1 <- with(df, x^2 + y^2) # A1对应的变量 df$z2 <- with(df, (x-1)^2 + (y-1)^2) # A2对应的变量 df$z3 <- with(df, (x+1)^2 + (y+1)^2) # A3对应的变量 ggplot() + # A1等高线层 stat_contour_filled( data = df, aes(x = x, y = y, fill = "A1"), geom = "contour_filled_pattern", pattern = "stripe", pattern_color = "black", breaks = c(0, 1, 2) ) + # A2等高线层 stat_contour_filled( data = df, aes(x = x, y = y, fill = "A2"), geom = "contour_filled_pattern", pattern = "stripe", pattern_color = "black", breaks = c(0, 1, 2) ) + # A3等高线层 stat_contour_filled( data = df, aes(x = x, y = y, fill = "A3"), geom = "contour_filled_pattern", pattern = "stripe", pattern_color = "black", breaks = c(0, 1, 2) ) + # 过滤冗余图例 scale_fill_pattern_discrete( limits = c("A1", "A2", "A3"), breaks = c("A1", "A2", "A3"), labels = c("A1", "A2", "A3") ) + # 调整图例条纹角度 guides( fill = guide_legend( override.aes = list( pattern_angle = c(45, 135, 0) ) ) )
关键注意事项
- 若你的
fill映射是基于after_stat(level)的分箱值,要确保limits指定的是实际生成的分箱标签,或提前将分箱变量处理为仅包含A1-A3的因子。 - 多个
stat_contour_filled层的fill映射标签必须和limits中的条目完全匹配,否则图例过滤会失效。
内容的提问来源于stack exchange,提问作者DreDev
相关产品推荐
相关产品推荐

