grid.text and positioning in viewports

2019-08-01 15:48发布

问题:

I am trying to create two plots side by side and annotate them:

setEPS(horizontal = FALSE, onefile = FALSE, paper = "special")

vplayout <- function(x, y) {
  viewport(layout.pos.row = x, layout.pos.col = y)
}

postscript(file="test.eps")
grid.newpage()
pushViewport(viewport(layout = grid.layout(1,2)))

plot1 <- qplot(rnorm(100))
grid.text('plot1')
print(plot1,vp=vplayout(1,1))

plot2 <- qplot(rnorm(10))
grid.text('plot2')
print(plot2,vp=vplayout(1,2))

dev.off()

The problem is that I can't get the labels to plot on each separate plot but instead they appear behind the two plots in the background. I tried to experiment with upViewport(), popViewport() and downViewport() but no success. Any ideas?

回答1:

You have to specify the viewport, where you want to print the text labels: grid.text('plot1', vp=vplayout(1,1)). You should also specify where in the viewport you want to print it. By default, it will print the text in the center. Moreover, the order in which you print matters. So first pirnt the plots and then the labels on top. Altogether your code should looks something like that:

grid.newpage()
pushViewport(viewport(layout = grid.layout(1,2)))

plot1 <- qplot(rnorm(100))
print(plot1,vp=vplayout(1,1))
grid.text('plot1', x=.5, y=.95, vp=vplayout(1,1))

plot2 <- qplot(rnorm(10))
print(plot2,vp=vplayout(1,2))
grid.text('plot2', x=.5, y=.95, vp=vplayout(1,2))

You could also just use ggtitle instead of grid.text. And if you use the gridExtra package, you can avoid viewports altogether:

require(gridExtra)
grid.arrange(
  plot1 + ggtitle('plot1'), 
  plot2 + ggtitle('plot2'),
  nrow=1)


标签: r ggplot2