简体   繁体   中英

ggforce facet_zoom - labels only on zoomed example

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 ):

dftxt <- dplyr::filter(df, example_values_x > 0.5) %>%
  dplyr::mutate( zoom = TRUE )      ## All entries to appear in the zoom panel only

You can now pass this new data frame to geom_label_repel , while telling facet_zoom() to use the zoom column to determine where the data should be drawn:

df %>% ggplot(aes(y = example_values_y, 
                  x = example_values_x)) +
  geom_point() +
  facet_zoom(x = example_values_x > 0.5, zoom.data=zoom) +   # Note the zoom.data argument
  geom_label_repel(data = dftxt, aes(label = labels))

Note that because the original df doesn't have a zoom column, facet_zoom() will treat it as NA and draw geom_point() in both panels, as desired:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM