I would like to label points in a scatterplot, but only those within the facet_zoom
panel. Here is an example:
library(ggplot2)
library(ggforce)
library(ggrepel)
library(magrittr)
labels <- letters
example_values_x <- rnorm(26)
example_values_y <- rnorm(26)
df <- data.frame(labels,
example_values_x,
example_values_y)
df %>% ggplot(aes(y = example_values_y,
x = example_values_x)) +
geom_point() +
facet_zoom(x = example_values_x > 0.5) +
geom_label_repel(data = filter(df, example_values_x > 0.5), aes(label = labels))
Any idea how to make it so the labels don't also appear on the non-zoomed panel?
NOTE: The following answer works with the GitHub version of ggforce. As of writing this, the version that's on CRAN appears to have a different interface for
facet_zoom()
, even though the package version is the same.First, take your subset of data being labeled and add a
zoom
column, specifying whether the data should be rendered in the zoomed panel (TRUE
), the original panel (FALSE
), or both (NA
):You can now pass this new data frame to
geom_label_repel
, while tellingfacet_zoom()
to use thezoom
column to determine where the data should be drawn:Note that because the original
df
doesn't have azoom
column,facet_zoom()
will treat it asNA
and drawgeom_point()
in both panels, as desired: