extract input data from ggplot object

2020-03-26 05:48发布

问题:

I know I can extract the data I plot in a ggplot2 plot using

p <- ggplot(df, aes(x, y)) + geom_point()
ggplot_build(p)$data

But data in this case is the data being plotted. Is there any way of getting the input data -- df in this case -- back?

回答1:

p itself is a list, you can get df with p$data.

A samll example:

library(ggplot2)
p <- ggplot(mtcars, aes(x = mpg, y = cyl)) + geom_point()
identical(p$data, mtcars)
# [1] TRUE


回答2:

The same approach but wrapped in a package/function is to 'capture the spirit of your ggplot calls' using library(ggghost)

library(ggghost)
library(ggplot2)

df <- data.frame(x = 1:20, y = 1:20, z= letters[1:20])

p %g<% ggplot(data = df, aes(x, y))
p <- p + geom_point()

rm(df)
ggghost::recover_data(p)
## this returns the data back to your environment


标签: r ggplot2