Skip to content

Instantly share code, notes, and snippets.

@burchill
Last active November 3, 2021 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burchill/6d621856337a25d2ea06a6f3e9ae32c1 to your computer and use it in GitHub Desktop.
Save burchill/6d621856337a25d2ea06a6f3e9ae32c1 to your computer and use it in GitHub Desktop.
Hide ggplot geoms without affecting legends, scaling, etc.
hide_geoms <- function(gg_obj) {
plot_data <- ggplot2::ggplot_build(gg_obj)
data_list = plot_data$data %>%
purrr::map(. %>% mutate(size=0,alpha=0))
plot_data$data <- data_list
return(ggplot2::ggplot_gtable(plot_data))
}
# Example
df1 <- tibble(
alp=runif(120,0,3),
bet=alp*2+1,
gam=rbinom(120,1,0.5))
df2 <- tibble(
alp=runif(120,3,10),
bet=-alp*2+10,
gam=rbinom(120,1,0.5))
g1 <- df1 %>%
ggplot(aes(x=alp,y=bet, color=as.factor(gam))) +
geom_point() +
geom_vline(xintercept = 5) +
geom_line(data=df2)
plot(g1)
plot(hide_geoms(g1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment