R大卫
R大卫

Reputation: 150

R: Is it possible to extract the original data from a gtable object created with grid.arrange and ggplot?

Problem description

I have created an gtable (also gTree grob gDesc) object myobj via myobj <- gridExtra::grid.arrange(g1,g2) from two ggplot objects g1,g2 some time ago and now I have to restore the data that I have used to create both ggplots. Is there a way to do this properly?

What I've tried so far

I have already tried to convert myobj using various functions, e.g., ggpubr::as_ggplot, resulting in an object with a waiver() as $data entry - so no success there - and I have also swept all the grobs entries in myobj where I in fact found the data points in the plot (looking like this

grobs.grobs.children.geom_point.points.5415.x1 
                                    0.04545455 

), which are, however, only the position coordinates $\in (0,1)$ w.r.t. the corresponding axis. Then I probably can get the axis + the axis range and then extrapolate the original data points. But that seems excessively laborious. Is there a more simple solution to this?

Reprex (sort of)

Not sure if this actually results in the same object as I have (because mine is almost 2y old), but for a start:

library(ggplot)

# plot 1
g1 <- ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(cols = vars(cyl))

# plot 2
g2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() + facet_grid(vars(cyl))

# create object
myobj <- gridExtra::grid.arrange(g1, g2, ncol=1)

# Now I would need some extract_data function to retrieve mpg and mtcars:
list_with_mpg_and_mtcars <- extract_data(myobj)

Upvotes: 1

Views: 818

Answers (1)

user13357985
user13357985

Reputation: 46

You can't; at this stage (namely, after ggplotGrob) the data have been processed into graphical objects and the mapping isn't usually reversible, much like an omelette.

If you are desperate for getting some values back you can inspect individual grobs corresponding to the plotted points, e.g.

myobj$grobs[[2]]$grobs[[2]]$children[[3]][c('x','y')]

$x
 [1] 0.525145067698259native 0.587040618955513native
 [3] 0.525145067698259native 0.89651837524178native 
 [5] 0.819148936170213native 0.954545454545455native
 [7] 0.474854932301741native 0.699226305609285native
 [9] 0.648936170212766native 0.819148936170213native
[11] 0.470986460348163native

$y
 [1] 0.233037353850445native  0.435264173310709native 
 [3] 0.425966388507938native  0.205143999442133native 
 [5] 0.0691638967016109native 0.12030171311685native  
 [7] 0.266741823760489native  0.143546175123777native 
 [9] 0.191197322237977native  0.0454545454545455native
[11] 0.339961879082309native 

Upvotes: 3

Related Questions