ggforce facet_zoom how to annotate only zoomed graphic

Viewed 1001

I would like to annotate the chart only in the zoomed-in area to give details about the highlighted data.

In the following example code, the idea is to show the text "zoom only" only in the zoomed-in area.

require(ggplot2)
require(ggforce)
ggplot(iris, aes(Petal.Length, Petal.Width, colour = Species)) +
    geom_point() +
    facet_zoom(x = Species == "versicolor") + 
    annotate("text", x=4, y=2, label="zoom only")

Text only in zoom (expected state): text only in zoom

Text in both (current state): text in both

Is there a way to do that?

1 Answers

We can dig into the object, and set that text to be transparent (alpha = 0):

p <- ggplot(iris, aes(Petal.Length, Petal.Width, colour = Species)) +
  geom_point() +
  facet_zoom(x = Species == "versicolor") + 
  annotate("text", x=4, y=2, label="zoom only")

pb <- ggplot_build(p)
pb$data[[2]][1, 'alpha'] <- 0
pg <- ggplot_gtable(pb)
plot(pg)

enter image description here

Related