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

R语言ggpattern移除Category图例并整合Product图例方法

实现方案

由于示例数据中Product与Category为固定一一对应关系(Apple、Banana属Fruit类无填充图案,Carrot属Vegetable类带条纹填充),无需保留独立的pattern映射图例,可通过以下代码实现需求:

# 加载依赖包
# remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
library(ggplot2)

# 构造示例数据
ex <- data.frame(
  Product = c("Apple","Apple","Apple","Banana","Banana","Banana","Carrot","Carrot","Carrot"),
  Price = c(1,2,3,2,5,3,4,2,3),
  Category = c("Fruit","Fruit","Fruit","Fruit","Fruit","Fruit","Vegetable","Vegetable","Vegetable"),
  Location = c("A1","A1","B1","B1","A1","B1","A1","B1","A1")
)

# 绘制柱状图
ggplot(ex, aes(x = Location, y = Price, fill = Product, pattern = Category)) +
  geom_bar_pattern(
    stat = 'identity', 
    position = position_dodge(preserve = "single"),
    color = "black", 
    pattern_fill = "black",
    pattern_angle = 45,
    pattern_density = 0.05,
    pattern_spacing = 0.025,
    pattern_key_scale_factor = 0.8
  ) + 
  scale_pattern_manual(values = c(Vegetable = "stripe", Fruit = "none")) +
  # 图例配置核心修改
  guides(
    # 隐藏Category对应的独立pattern图例
    pattern = "none",
    # 将图案效果整合到Product的fill图例中
    fill = guide_legend(
      override.aes = list(
        # 向量顺序与Product默认因子层级一致:Apple、Banana、Carrot
        pattern = c("none", "none", "stripe")
      )
    )
  ) +
  theme_bw() +
  theme(text = element_text(size = 13))

关键改动说明

  • 移除独立pattern图例:在guides()中为pattern参数传入"none",即可直接隐藏Category对应的单独图例,无需额外修改主题参数。
  • 合并图案到fill图例:在fill对应的图例配置中,通过override.aes为每个Product的图例标识匹配对应的pattern属性,即可让Product图例直接显示正确的填充效果,最终仅保留一个合并后的图例。
  • 若调整过Product的因子顺序,需要同步修改override.aes中pattern向量的取值顺序,保证和图例展示的Product顺序一一对应即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:03:22