由'plot'和'ggplot'生成的图表并排显示

17

有没有办法在R中将plot函数生成的图和ggplot函数生成的图放在同一页并排显示?

使用parmultiplot函数可以轻松地将同一函数创建的图放在一个页面上,但我无法解决上述问题。


1
你可以查看 gridExtra 包。我认为它可以做到这一点。 - Justin
2个回答

26

你可以使用gridBase包和viewPorts来实现这一点。

library(grid)
library(gridBase)
library(ggplot2)

# start new page
plot.new() 

# setup layout
gl <- grid.layout(nrow=1, ncol=2)
# grid.show.layout(gl)

# setup viewports
vp.1 <- viewport(layout.pos.col=1, layout.pos.row=1) 
vp.2 <- viewport(layout.pos.col=2, layout.pos.row=1) 
# init layout
pushViewport(viewport(layout=gl))
# access the first position
pushViewport(vp.1)

# start new base graphics in first viewport
par(new=TRUE, fig=gridFIG())

plot(x = 1:10, y = 10:1)

# done with the first viewport
popViewport()

# move to the next viewport
pushViewport(vp.2)

ggplotted <- qplot(x=1:10,y=10:1, 'point')
# print our ggplot graphics here
print(ggplotted, newpage = FALSE)

# done with this viewport
popViewport(1)

enter image description here

这个示例是这篇博客文章的修改版,原作者为Dylan Beaudette


你给出了一个非常整洁的答案。谢谢。 - Elaine
gridFIG() 函数来自哪里? - Paul Rigor

2

是的。它们都是基于网格的图形系统,并返回图形对象。请查看gridExtra包中的grid.arrange函数。


这句话应该是说如果它们都是基于网格的图形系统,对吗? - mnel
我可能读的是早期版本,上面写着“lattice”和“ggplot2”……或者是我喝的这瓶啤酒有特殊的功效。你回答中的一个赞就是我点的。 - IRTFM
绘图函数不是基于网格的。这可能就是您所指的,DWin?然而,我已经阅读到有办法将绘图嵌入到网格系统中。 - JAponte

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接