Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

gridextra - Combining grid.table and base package plots in R figure

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...