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

ggplot中使用scale_color_manual自定义图例,颜色与代码不匹配

问题原因及解决方案

核心原因

  1. 硬编码颜色未关联美学映射:你直接在geom_sf中用col和fill硬编码颜色,这种方式绕过了ggplot的美学映射系统,后续的scale_color_manual无法对这些硬编码的颜色生效。当前图例显示的是geom_sf中设置的边框色(Vista的col="maroon"),而非你期望的填充色。
  2. 尺度类型不匹配:scale_color_manual控制的是线条/边框颜色的尺度,若你想展示填充色的图例,应该使用scale_fill_manual。
  3. 多图层未统一映射:两个独立的geom_sf图层各自设置颜色,ggplot无法自动将这些颜色与你定义的图例标签("Vista"/"Reno")关联,导致图例与实际颜色不匹配。

修复方案

正确的做法是将两个shapefile合并为一个数据框,新增分组变量,通过美学映射(aes)绑定颜色,再用尺度函数统一设置颜色:

步骤1:合并数据并添加分组列

# 给两个数据集添加分组标识
Vista_rebuf$area <- "Vista"
Reno_rebuf$area <- "Reno"

# 合并为一个数据框
combined_data <- rbind(Vista_rebuf, Reno_rebuf)

步骤2:重构绘图代码

library(ggplot2)
library(ggspatial)

plot <- ggplot(data = combined_data) +
  geom_sf(aes(col = area, fill = area), show.legend = "polygon") +
  # 设置边框色和填充色的尺度
  scale_color_manual(values = c("Vista" = "maroon", "Reno" = "dark green"),
                     breaks = c("Reno", "Vista")) +
  scale_fill_manual(values = c("Vista" = "purple", "Reno" = "green"),
                    breaks = c("Reno", "Vista")) +
  ggspatial::annotation_scale(location = "br", bar_cols = c("grey60", "white")) +
  ggspatial::annotation_north_arrow(
    location = "br", which_north = "true",
    pad_x = unit(0.1, "in"), pad_y = unit(0.3, "in"),
    style = ggspatial::north_arrow_nautical(fill = c("grey40", "white"), line_col = "grey20")
  ) +
  ggtitle("RFC Forecasting Area") +
  theme(
    plot.title = element_text(hjust = 0.5),
    legend.title = element_text(size = 20),
    legend.text = element_text(size = 14)
  )

plot

关键说明

  • 通过aes(col = area, fill = area)将边框色和填充色与分组变量area绑定,让ggplot识别颜色映射关系。
  • 用scale_color_manual设置边框色,scale_fill_manual设置填充色,两者分别对应你最初的硬编码颜色。
  • show.legend = "polygon"确保图例展示多边形的填充和边框样式,避免重复图例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:07:35