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:
The second plot looks like this:
Putting them together with patchwork places the first plot where I want it to be, but flips it 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.
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
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.
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
being the combination of plot2
and plot1