How do I create two inserted plots by zooming in on two different areas? The original plot was made with `ggplot2`

550 Views Asked by At

I made a plot using ggplot2. From this plot, I want to highlight and zoom in on two different areas. To do this I used the ggforce package and the facet_zoom( ) function. However, this function only creates one inset plot, and I can find no information on how to make a second one.

library(ggplot2)
library(ggforce)

ggplot(data = mtcars,
       aes(x = mpg,
           y = disp,
           color = factor(cyl),
           shape = factor(carb))) +
  geom_point() +
  facet_zoom(xlim = c(15, 20),
             ylim = c(200, 300),
             horizontal = FALSE)

enter image description here

In addition to the inset plot shown, I would like to add this one:

facet_zoom(xlim = c(30, 35),
           ylim = c(0, 100),
           horizontal = FALSE)

How can I put the second plot on the right side of the first?

1

There are 1 best solutions below

0
Quinten On

You could create a variable with a categorical id based on the ranges you want to zoom on. With this variable, you could use xy argument with split to zoom on two areas in facet_zoom like this:

library(ggplot2)
library(ggforce)
library(dplyr)

mtcars |>
  mutate(area = case_when(mpg >= 15 & mpg <= 20 & disp >= 200 & disp <= 300 ~ "A",
                          mpg >= 30 & mpg <= 35 & disp >= 0 & disp <= 100 ~ "B")) |>
  ggplot(aes(x = mpg,
             y = disp,
             color = factor(cyl),
             shape = factor(carb))) +
  geom_point() +
  facet_zoom(xy = area  %in% c("A", "B"), split = TRUE)

Created on 2023-04-14 with reprex v2.0.2