Search code examples
rggplot2patchwork

inset_element from patchwork is flipping the inset upside down


I'm trying to use patchwork's inset_element function to make a map with an inset. I've toyed with the placement and various other values and am happy with where my inset has been placed, but the inset map is getting flipped upside down.

Now, I've created a reproducible example using figures instead of maps made by geom_sf, and it reproduces the same behavior:

library("ggplot2")
library("patchwork")

set.seed(0922023)

a <- rnorm(1000)
b <- rnorm(1000)
c <- rnorm(1000)
d <- c + rnorm(1000)

df <- cbind.data.frame(a, b, c, d)

plot1 <- ggplot(df, aes(x = a, y = b)) +
  geom_point()

plot1

plot2 <- ggplot(df, aes(x = c, y = d)) +
  geom_point()

plot2

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

combined_plot <- plot2 + inset

combined_plot

The first plot looks like this:

First plot example

The second plot looks like this:

Second plot example

Putting them together with patchwork places the first plot where I want it to be, but flips it upside down!

Patchwork inset is flipped upside down

Now, these plots aren't pretty because I'm just making a minimum working example, but when I do this with my actual data (and the placement looks nice), I get the same error. Here's the kicker: if I wanted to, I could flip plot1 and have it go into the inset upside down so it ends up right-side up, but there are two issues with this.

  1. My actual example being a map means it's non-trivial to flip upside down.
  2. It seems like in principle this shouldn't be happening at all, and while that workaround might work, it doesn't really get at the underlying problem.

I've tried messing with the top and bottom arguments of inset_element. For example, the following code puts the plot right-side-up, but in the bottom-right corner. I need it to be in the top-left corner.

# alternative
inset <- inset_element(
  plot1,
  left = 0.7,
  bottom = 0,
  right = 1,
  top = 0.3
)

combined_plot <- plot2 + inset

combined_plot

Alternative patchwork inset is right-side-up, but not in the correct position

Maybe I'm just not understanding the arguments of inset_element correctly, but I haven't found helpful information online to fix this. Thanks for the help in advance.


Solution

  • bottom= and top= are based on the bottom of the plot, not the top. If you swap so that bottom=0.7 and top=1, you get more appropriate results.

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

    combined inset plot

    being the combination of plot2

    plot2

    and plot1

    plot1