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

如何在R ggplot中移除重复的DMA边界图例

问题解决:移除多余的DMA图例

你遇到的多余DMA图例,是因为在scale_fill_manual里同时指定了aesthetics = c("fill", "color"),再加上后续使用new_scale_color(),导致生成了额外的color图例。只需调整两处代码即可修复:

  1. 在DMA的geom_sf图层中,仅绑定fill = DMA,移除color = DMA的映射(已通过override.aes设置图例边框颜色)
  2. 将scale_fill_manual中的aesthetics参数改为仅保留"fill"

修改后的完整代码

# Filter out zero counts and apply binning
ok_cities_correct_clean <- ok_cities_correct_clean %>%
  filter(COUNT > 0) %>%
  mutate(
    color_gradient = cut(
      COUNT,  # Cut the COUNT values into the specified ranges
      breaks = c(0, 10, 20, 30, Inf),  # Include 0 as the lower bound for first bin
      labels = c("1 - 10", "11 - 20", "21 - 30", "> 30"),  # Correct number of labels
      right = TRUE  # Ensure the upper bound is included in each bin
    )
  )

# Define color palettes
cities_urban <- c("lightblue", "lightskyblue", "dodgerblue", "darkblue")
names(cities_urban) <- labels


cities_rural <- c("lightpink", "lightcoral", "firebrick", "darkred")
names(cities_rural) <- labels



ggplot() +
  
  # Add OK counties
  geom_sf(
    data = ok_counties_reproj,
    fill = "#f5f5f5",
    color = "black",
    size = 0
  ) +
  
  # Add DMA 仅绑定fill映射
  geom_sf(
    data = ok_DMA,
    aes(fill = DMA),
    linewidth = 1.5,
    alpha = 0.75,
    show.legend = c(fill = TRUE)
  ) +
  
  # OK counties (border, no fill)
  geom_sf(
    data = ok_counties_reproj,
    fill = NA,
    color = "black",
    size = 1
  ) +
  
  # Set fill colors for DMA 仅作用于fill美学
  scale_fill_manual(
    values = c(
      "Tulsa, OK" = "#4575b4",
      "Oklahoma City, OK" = "#5ab4ac"
    ),
    aesthetics = "fill",
    guide = guide_legend(override.aes = list(
      color = c("#5ab4ac", "#4575b4")
    ))
  ) +
  
  new_scale_color() +
  
  # Add cities with color_gradient based on urban/rural classification
  geom_sf(
    data = ok_cities_correct_clean %>%
      filter(COUNT > 0, CLASSIF == "Urban"),
    aes(size = COUNT, color = color_gradient)
  ) +
  
  scale_color_manual(
    values = cities_urban, na.value = "gray", name = "Urban"
  ) +
  
  new_scale_color() +
  
  # Add cities with color gradient based on urban/rural classification
  geom_sf(
    data = ok_cities_correct_clean %>%
      filter(COUNT > 0, CLASSIF == "Rural"),
    aes(size = COUNT, color = color_gradient)
  ) +
  
  scale_color_manual(
    values = cities_rural, na.value = "gray", name = "Rural"
  ) +
  
  scale_size_continuous(
    range = c(1, 10),
    name = "Frequency of Mentions"
  )

修复原理

原本在DMA图层同时绑定fill和color映射,再配合scale_fill_manual同时作用于两种美学属性,导致生成了两个DMA图例(一个fill、一个color)。去掉color = DMA的映射后,仅通过guide_legend(override.aes)设置图例边框样式,既保留了DMA区域的视觉效果,又不会生成多余图例。

地图展示:
地图展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 20:55:20