You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggpattern白色图案(填充与图案为不同变量):如何为图案图例加灰色背景?

解决图例显示问题的方案

针对你遇到的两个图例问题,直接修改代码即可实现需求:

  1. 给图案图例的方框添加灰色填充,让白色图案更醒目
  2. 移除颜色图例中的图案,只保留纯色填充

修改后的完整代码如下:

library(ggplot2)
library(ggpattern)

dataset <- mtcars

dataset$cyl <- as.factor(dataset$cyl)
dataset$gear <- as.factor(dataset$gear)

ggplot(data=dataset,
       aes(x=gear, y=mpg, pattern=cyl, fill=gear)) +
  stat_boxplot(inherit.aes=T, geom ='errorbar', width = 0.6, lwd=1, 
               position=position_dodge(0.8), color="black")+
  geom_boxplot_pattern(width=0.8, lwd=1, color="black",alpha=0.6, 
                       outlier.size=1,
                       pattern_fill = "white",
                       pattern_angle = 45,
                       pattern_density = 0.4,
                       pattern_spacing = 0.03,
                       pattern_key_scale_factor = 1,
                       pattern_alpha = 1,
                       pattern_linetype=0,
                       show.legend = T) + 
  scale_pattern_manual(values=c(`4`="none", `6`="stripe", `8`="crosshatch")) +
  scale_fill_manual(values=c(`3`="red", `4`="blue", `5`="green"))+
  scale_y_continuous(limits = c(0, NA), expand=expansion(mult=c(0,0.2))) +
  # 自定义图例设置
  guides(
    # 给图案图例添加灰色填充
    pattern = guide_legend(override.aes = list(fill = "gray80")),
    # 移除颜色图例中的图案
    fill = guide_legend(override.aes = list(pattern = "none"))
  ) +
  # 若需要分面,替换为正确的ggplot2分面函数(原代码facet.by参数无效)
  facet_wrap(~cyl)

关键修改说明:

  • guides(pattern = guide_legend(override.aes = list(fill = "gray80"))):强制图案图例的填充色为浅灰色,白色图案叠加在灰色背景上会更清晰可见。
  • guides(fill = guide_legend(override.aes = list(pattern = "none"))):强制颜色图例的图案类型为none,让颜色图例只显示纯色填充,消除图案干扰。
  • 原代码中的facet.by=cyl参数不符合ggplot2语法,替换为facet_wrap(~cyl)实现分面(若不需要分面可删除此行)。

内容的提问来源于stack exchange,提问作者Elizabeth W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:22:34