2

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?

Daniel Valencia C.
  • 2,159
  • 2
  • 19
  • 38
  • 1
    do you need to use facet_zoom? Otherwise, this could help: https://stackoverflow.com/a/66409862/2761575 – dww Apr 12 '23 at 11:17
  • Echoing @dww's point, if you have multiple distinct areas that you want to zoom into, you may find it simpler to create separate zoomed-in plots, mark out their positions on the full plot, then stitch everything together using one of the usual options for arranging multiple plots (e.g. patchwork, cowplot, egg, gridExtra). The trapezoid shapes employed by `facet_zoom` to convey zooming are nice, but I don't think the usage is so ubiquitous that your readers won't understand if you indicate the zoom in some other form (e.g. draw arrows, add explanatory text, etc.). – Z.Lin Apr 16 '23 at 05:41
  • For historical interest, this question had been asked [before](https://stackoverflow.com/q/58627538/8449629) and didn't get a real answer back then, either. – Z.Lin Apr 16 '23 at 10:27

1 Answers1

2

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

Quinten
  • 35,235
  • 5
  • 20
  • 53