get_plot_data: Extract data behind a ggplot

View source: R/get_plot_data.R

get_plot_dataR Documentation

Extract data behind a ggplot

Description

Extract the data that was passed into the ggplot2() or qplot() call, with only the columns that are mapped to aesthetics.

Usage

get_plot_data(plot = ggplot2::last_plot())

Arguments

plot

The plot to extract data from. Currently only supports ggplot objects. Defaults to the last ggplot modified or created.

Details

If an expression is mapped to an aesthetic, it is added as a column in the result, with the expression as the column name. You may need to use backticks (e.g. ⁠`column expression`⁠) to refer to those columns.

Mappings provided in subsequent layers are also added if those layers don't have their own data. Layers which have their own data (passed in as geom_xxxx(data=...)) are ignored, as these are often used to add annotations or guides.

Value

A data frame with the extracted data. Each column has been mapped to some aesthetic in the plot.

Examples

library(ggplot2)

# Extract the data that was passed into the plot
sample_plot <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
get_plot_data(sample_plot) # -> data.frame with columns: mpg, hp

# Also picks up mappings in subsequent layers
sample_plot <-
  ggplot(iris, aes(Petal.Width, Petal.Length)) +
  geom_density2d() +
  geom_point(aes(colour=Species))
get_plot_data(sample_plot)
# -> data.frame with columns: Petal.Width, Petal.Length, Species

# Supports expression mappings
sample_plot <- qplot(mpg - mean(mpg), hp^2, data=mtcars)
get_plot_data(sample_plot)
# -> data.frame with columns: `mpg - mean(mpg)`, `hp^2`

# Facet variables are included:
sample_plot <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  facet_wrap(~cyl)

get_plot_data(sample_plot)
# -> data.frame with columns: `wt`, `mpg`, `cyl`


djpr-data/djprtheme documentation built on April 15, 2023, 2:47 a.m.