rggplot2legendggspatialggnewscale

Legend key color when combining ggOceanMaps and ggspatial


I am trying to combine basemap from ggOceanMaps with geom_spatial_point and having the geom_spatial_point having a new color scale.

When I combine these two, the legend.key background color remains dark grey despite setting it to white in the theme. If I remove the basemap, there is no issues.

Any thoughts?

Here's the code (and example image showing the problem):

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))) +
  theme(legend.key = element_rect(fill = "white", color = NA))

I would like the legend.key background to be white.


Solution

  • I encountered a similar issue when answering a related question. To me it looks as if the grey background of the legend key stems from the base map fill. And the only option I have found to fix this issue is to override the fill aes via the override.aes= argument of guide_legend. However, as you are using ggnewscale you have to override the fill_new (aka the renamed fill) aes.

    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(fill_new = NA)
        )
      )
    

    enter image description here