grid.text and positioning in viewports

2019-08-01 16:05发布

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?

标签: r ggplot2
1条回答
仙女界的扛把子
2楼-- · 2019-08-01 16:49

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)
查看更多
登录 后发表回答