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

ggOceanMaps与ggspatial结合时图例键背景颜色异常问题

解决ggOceanMaps底图与geom_spatial_point结合时图例键背景色问题

ggOceanMaps的basemap()会自带内置主题,其中默认把legend.key的背景设为深灰色,即便后续用theme()设置白色背景,也会被这个内置主题覆盖——尤其是用new_scale_fill()新增填充刻度后,新图例依然继承底图的深色背景。

下面提供两种可行的解决办法:

方法一:在填充刻度中自定义图例样式

直接在scale_fill_manual里通过guide参数指定图例键的背景色:

library(ggspatial)
library(ggnewscale)
library(pals)
library(ggOceanMaps)

test <- data.frame(lon = c(-150:-120), lat = c(20:50), toppid = c(rep(c(10:15), each = 5),15))

basemap(limits = c(110, -110, 20, 60), rotate = TRUE,bathy.style = "rcb") +
  new_scale_fill() +
  geom_spatial_point(crs = 4326, data = test, aes(x = lon, y = lat, fill = factor(toppid)), size = 2, pch = 21, color = "black") +
  scale_fill_manual(
    values = as.vector(alphabet(6)),
    guide = guide_legend(override.aes = list(background = element_rect(fill = "white")))
  ) +
  theme(legend.key = element_rect(fill = "white", color = NA))

方法二:先更新主题再添加图层

在basemap之后立即用theme_update()全局修改图例键样式,确保后续图层继承白色背景:

library(ggspatial)
library(ggnewscale)
library(pals)
library(ggOceanMaps)

test <- data.frame(lon = c(-150:-120), lat = c(20:50), toppid = c(rep(c(10:15), each = 5),15))

basemap(limits = c(110, -110, 20, 60), rotate = TRUE,bathy.style = "rcb") +
  theme_update(legend.key = element_rect(fill = "white", color = NA)) +
  new_scale_fill() +
  geom_spatial_point(crs = 4326, data = test, aes(x = lon, y = lat, fill = factor(toppid)), size = 2, pch = 21, color = "black") +
  scale_fill_manual(values = as.vector(alphabet(6)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 09:49:54