Combining grid.table and base package plots in R figure

会有一股神秘感。 提交于 2019-12-01 09:40:11

问题


I am trying to combine tables from grid.table together with plots from base package into a single plot. As far as I understand, grid.table produced the same type of output as the one produced by ggplot. So the problem is similar to the one in this thread:

Combine base and ggplot graphics in R figure window

I tried to apply the solution from that thread, but it does not work for me. The first table is placed in the correct position, but the second is not. The solution from that thread works if I have no more than 1 table produced by grid.table. What are the modifications I have to do, to make it work for several tables?

Here is my code:

library(gridBase)
library(gridExtra)

pdf("test-grid.pdf")
par(mfrow=c(2,2))

data(mtcars)
sample_table1 <- matrix(1,3,5)
sample_table2 <- matrix(2,2,2)

plot.new()
vps <- baseViewports()
pushViewport(vps$figure)
vp1 <-plotViewport()
grid.table(sample_table1)

plot.new()
vps <- baseViewports()
pushViewport(vps$figure)
vp1 <-plotViewport()
grid.table(sample_table2)

plot(mtcars$mpg, mtcars$cyl)
plot(mtcars$disp, mtcars$hp)

dev.off()

回答1:


You forgot to pop the viewport, so your second grid.table was still in first viewport. So just use popViewport() after each grid.table commands and it should work.

library(gridBase)
library(gridExtra)

pdf("test-grid.pdf")
par(mfrow=c(2,2))

data(mtcars)
sample_table1 <- matrix(1,3,5)
sample_table2 <- matrix(2,2,2)

plot.new()
vps <- baseViewports()
pushViewport(vps$figure)
vp1 <-plotViewport()
grid.table(sample_table1)
popViewport()

plot.new()
vps <- baseViewports()
pushViewport(vps$figure)
vp1 <-plotViewport()
grid.table(sample_table2)
popViewport()

plot(mtcars$mpg, mtcars$cyl)
plot(mtcars$disp, mtcars$hp)

dev.off()


来源:https://stackoverflow.com/questions/23426436/combining-grid-table-and-base-package-plots-in-r-figure

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