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

如何在ggplot箱线图中按period设置异常点颜色且不新增图例

解决方案

直接修改geom_boxplot的映射并隐藏多余图例即可实现需求,以下是两种方案:

方案一:使用默认配色

ggplot(dat_bee_merged, aes(x = factor(region), y = colony_loss_proportion)) +
  geom_boxplot(aes(fill = factor(period), outlier.colour = factor(period))) +
  geom_hline(yintercept = median(dat_bee_merged$colony_loss_proportion), color = "red", linetype = "dashed", size = 1) +
  labs(x = "Climatic Regions", y = "Normalized colony loss", fill = "period") +
  ggtitle("Honeybee colony loss across different climatic regions and periods") +
  guides(color = "none") +
  theme_minimal()

关键改动说明:

  • 在geom_boxplot的aes中添加outlier.colour = factor(period),让异常点颜色与箱线图填充色绑定
  • 用guides(color = "none")隐藏异常点颜色生成的多余图例,只保留填充色的周期图例

方案二:自定义配色(可选)

如果需要指定特定颜色,可同时设置填充色和异常点颜色为同一套自定义值:

# 自定义周期配色,替换为你需要的颜色代码或名称
custom_palette <- c("period_1" = "#2E86AB", "period_2" = "#F26430")

ggplot(dat_bee_merged, aes(x = factor(region), y = colony_loss_proportion)) +
  geom_boxplot(aes(fill = factor(period), outlier.colour = factor(period))) +
  geom_hline(yintercept = median(dat_bee_merged$colony_loss_proportion), color = "red", linetype = "dashed", size = 1) +
  labs(x = "Climatic Regions", y = "Normalized colony loss", fill = "period") +
  ggtitle("Honeybee colony loss across different climatic regions and periods") +
  scale_fill_manual(values = custom_palette) +
  scale_color_manual(values = custom_palette) +
  guides(color = "none") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:52:16