Search code examples
rggplot2legend-properties

Add a layer without overlapping the previous parameters in Ggplot


I need these two things to happen:

  1. Layer (map) 1: These map elements in the legend should not have border line (colour = NA)!

  2. Layer (map) 2: This map element in the legend should have a red border line (colour = "red").

Problem: When I add "layer 2", all map elements in the legend of "layer 1" also change their border to red.

Note: This only happens in the legend! The map borders do not change, they are plotted correctly.

Here is an example to run in R:

Running only layer 1, is correct, the elements on the map and the legend have no border color:

library("sf"); library("ggplot2")
library("rnaturalearth"); library("rnaturalearthdata") #packages containing the example layers

layer1 <- ne_countries(returnclass = "sf")

ggplot() +
  geom_sf(data = layer1, #layer 1
          aes(fill = as.factor(region_un)), # example of variable
          colour = NA) # removing the borders

Layer 1 with no border color in the element of legend:

img1

However, when adding a second layer, all elements have a red border, including layer 1:

layer2 <- layer1[layer1$region_un == "Africa", ] # layer 2

ggplot() +
  geom_sf(data = layer1, #layer 1
          aes(fill = as.factor(region_un)),
          colour = NA) + # removing the borders
  geom_sf(data = layer2 , #layer 2
          aes(fill = region_wb), 
          alpha = 0, # transparent fill
          colour = "red") # red border line 

Layer 1 and layer 2, with all elements of legend with red border color:

img2


Solution

  • library("sf"); library("ggplot2")
    library("rnaturalearth"); library("rnaturalearthdata") #packages containing the example layers
    
    layer1 <- ne_countries(returnclass = "sf")
    
    layer2 <- layer1[layer1$region_un == "Africa", ] # layer 2
    
    ggplot() +
      geom_sf(data = layer1, #layer 1
              aes(fill = as.factor(region_un)),
              colour = NA) + # removing the borders
      geom_sf(data = layer2 , #layer 2
              aes(fill = region_wb), 
              alpha = 0, # transparent fill
              colour = "red") + # red border line 
      guides(fill = guide_legend ( 
                       override.aes = list(colour = c(NA, NA, NA, NA, NA, "red", 
                                                      NA, NA, "red"))))
    

    enter image description here