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

R语言ggplot绘图中图例无法显示问题求助

解决ggplot图例不显示的问题

问题出在你同时在geom_col的aes里定义了fill分组,又在aes外面直接指定了fill颜色——后者会覆盖美学映射,导致ggplot无法生成图例。因为图例是基于aes里的映射关系创建的,硬编码的颜色不会触发图例生成。

修正后的代码如下:

ggplot() +
  geom_col(data = r, aes(x, value, fill = "Rain Forecast Information"), width = 0.6, alpha = 0.7) +
  geom_col(data = d, aes(x, value, fill = "No Forecast Information"), width = 0.6, alpha = 0.7) +
  labs(title = "预期损失(美元)与购奶量关系", 
       x = '购买加仑数', 
       y = "预期损失",
       fill = "信息类型") +  # 可自定义图例标题
  scale_x_continuous(breaks = 1:10, labels = c(1:10)) +
  scale_fill_manual(values = c(
    "Rain Forecast Information" = 'blue',
    "No Forecast Information" = "red"
  )) +
  theme(panel.grid.major.y = element_line(color = 'darkgray'),
        panel.grid.minor.y = element_line(color = 'darkgray'),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        legend.position = "bottom")

修改要点:

  • 移除每个geom_col外部的fill参数,仅在aes中保留fill的分组标识
  • 添加scale_fill_manual,手动绑定分组名称与对应颜色
  • 可通过labs(fill = ...)设置图例的自定义标题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:07:09