rggplot2patchwork

How to delete legend from inset but keep legend in the main plot in a patchwork layout in R?


I need to create a plot layout with two main plots having an inset each. I'd like to keep the legend in the main plots (positioned inside the plot), but I need to show the insets without any legend. I tried different options within guides =, but it didn't work. I set theme(legend.position = "none") in the inset plots.

This is what I got: enter image description here

This is the code I used:

library(patchwork)
library(ggplot2)
data(mtcars)

######## Plot 1
plot1 <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) +
  geom_point() +
  labs(title = "Plot 1")

inset.plot1 <- ggplot(mtcars, aes(x = wt, y = qsec, color = factor(gear))) +
  geom_point() +
  theme(legend.position = "none") +
  labs(title = "inset Plot 1")

layout.plot1 <- plot1 + 
  inset_element(inset.plot1, 
                left=0.7, bottom=0.7, right=1, top=1)

####### Plot 2
plot2 <- ggplot(mtcars, aes(x = disp, y = drat, color = factor(carb))) +
  geom_point() +
  labs(title = "Plot 2")

inset.plot2 <- ggplot(mtcars, aes(x = hp, y = wt, color = factor(am))) +
  geom_point() +
  theme(legend.position = "none") +
  labs(title = "Inset Plot 2")

layout.plot2 <- plot2 + 
  inset_element(inset.plot2, 
                left=0.7, bottom=0.7, right=1, top=1)


####### Final layout
Final.layout <- 
  layout.plot1 + layout.plot2 +
  plot_layout(guides = "keep") &
  theme(legend.position = c(0.9, 0.15))

I need to show the insets without the legends.


Solution

  • One option would be to set the position for the main plot legends separately in plot1/2 instead of using & which will set the position for all elements of the patch including the inset plots:

    library(patchwork)
    library(ggplot2)
    
    ######## Plot 1
    plot1 <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) +
      geom_point() +
      labs(title = "Plot 1") +
      theme(legend.position = c(0.9, 0.15))
    
    inset.plot1 <- ggplot(mtcars, aes(x = wt, y = qsec, color = factor(gear))) +
      geom_point() +
      theme(legend.position = "none") +
      labs(title = "inset Plot 1")
    
    layout.plot1 <- plot1 +
      inset_element(inset.plot1,
        left = 0.7, bottom = 0.7, right = 1, top = 1
      )
    
    ####### Plot 2
    plot2 <- ggplot(mtcars, aes(x = disp, y = drat, color = factor(carb))) +
      geom_point() +
      labs(title = "Plot 2") +
      theme(legend.position = c(0.9, 0.15))
    
    inset.plot2 <- ggplot(mtcars, aes(x = hp, y = wt, color = factor(am))) +
      geom_point() +
      theme(legend.position = "none") +
      labs(title = "Inset Plot 2")
    
    layout.plot2 <- plot2 +
      inset_element(inset.plot2,
        left = 0.7, bottom = 0.7, right = 1, top = 1
      )
    
    
    ####### Final layout
    Final.layout <-
      layout.plot1 + layout.plot2 +
        plot_layout(guides = "keep")
    
    Final.layout
    

    enter image description here