ggforce facet_zoom - labels only on zoomed example

有些话、适合烂在心里 提交于 2020-01-15 03:23:05

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/45221783/ggforce-facet-zoom-labels-only-on-zoomed-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!