質問

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()
役に立ちましたか?

解決

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()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top