将基本r图保存为可以在多图中绘制的对象 [英] saving a base r plot as an object that can be plotted in a multiplot

查看:117
本文介绍了将基本r图保存为可以在多图中绘制的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题来自相关帖子,其中显示了如何使用pryr包中的%<a-%函数,可以轻松地将图形存储为r对象.伟大的!但是,我现在想创建一个多图,将一个基本r图与2个ggplot数字结合起来.我在下面使用grid.arrange.

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.

使用基础r cars数据,我可以制作两个ggplot图形.

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")

然后用plot制作图形,并使用pryr包中的%<a-%函数将图形另存为对象.光滑

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

最后,我想将3个图形组合成一个图,如下所示.

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)))

代码产生以下错误:

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

如何保存基本r图以与其他ggplot图形组合?

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

推荐答案

正如@MrFlick正确指出的那样,

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)))

这篇关于将基本r图保存为可以在多图中绘制的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆