saving a base r plot as an object that can be plotted in a multiplot

匆匆过客 提交于 2019-12-08 06:35:36

问题


This question builds from a related post which shows how to easily store a plot as an r object with the %<a-% function from the pryr package. Great! However, I now want to create a multiplot that combines a base r plot with 2 ggplot figures. I am using grid.arrange below.

Using the base r cars data I can make two ggplot figures.

library(ggplot2)
library(pryr)
library(gridExtra)

Fig1 <- qplot(speed, data=cars, geom="histogram")
Fig2 <- qplot(dist, speed, data=cars, geom="point")

I then make a figure with plot, and save the figure as an object using the %<a-% function from the pryr package. Slick.

Fig3 %<a-% plot(cars$speed, cars$dist)
Fig3

Lastly, I want to combine the 3 figures into a single plot as shown below.

Figs <- grid.arrange(Fig1, Fig2, Fig3,
                     layout_matrix = rbind(c(1,1,1,2,2), c(1,1,1,2,2), c(3,3,3,3,3)))

The code produces the following error:

Error in gList(list(grobs = list(list(x = 0.5, y = 0.5, width = 1, height = 1,  : 
  only 'grobs' allowed in "gList"

How can I save an base r plot to be combined with additional ggplot figures?


回答1:


As correctly noted by @MrFlick, the accepted answer linked here is a better approach than the %<a-% function which does not store a grid.

The code below produces the desired result.

library(ggplot2)
library(gridExtra)
library(gridGraphics)
library(grid)

Fig1 <- qplot(speed, data=cars, geom="histogram")
Fig2 <- qplot(dist, speed, data=cars, geom="point")

plot(cars$speed, cars$dist)
grid.echo()
Fig3 <- grid.grab()

Figs <- grid.arrange(Fig1, Fig2, Fig3,
                     layout_matrix = rbind(c(1,1,1,2,2), c(1,1,1,2,2), c(3,3,3,3,3)))


来源:https://stackoverflow.com/questions/42723141/saving-a-base-r-plot-as-an-object-that-can-be-plotted-in-a-multiplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!