Below is code and a graph.
The graph has three facets. Where in the_plot
can I find it has three facets? Yes, I could get that from the mtcars
data frame, or the_plot$data
, but I don't want to recreate the data analysis. Rather, I want to inspect the graphical elements of the_plot
, so I don't have to duplicate application logic in multiple places. the_plot$facet
doesn't show anything I recognize, nor do the other plot variables.
I'm using tidyverse 1.3.0.
library(tidyverse)
data(mtcars)
the_plot<-ggplot(mtcars, aes(mpg, disp, group=cyl)) + facet_wrap(~cyl) + geom_point()
the_plot
The facet approach partitions a plot into a matrix of panels. Each panel shows a different subset of the data. This R tutorial describes how to split a graph using ggplot2 package. There are two main functions for faceting : facet_grid()
facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.
facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner. You can control how the ribbon is wrapped into a grid with ncol , nrow , as.
you can access the ggplot data with the gg_build() - function
out <- ggplot_build(the_plot)
length(levels(out$data[[1]]$PANEL))
[1] 3
Another method
library(ggplot2)
data(mtcars)
the_plot<-ggplot(mtcars, aes(mpg, disp, group=cyl)) + facet_wrap(~cyl) + geom_point()
pb <- ggplot_build(the_plot)
pb$layout$layout$PANEL
#> [1] 1 2 3
#> Levels: 1 2 3
Created on 2020-04-21 by the reprex package (v0.3.0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With