how do I get rid of random background grid from arrangeGrob

房东的猫 提交于 2019-12-07 13:41:43

问题


I need to wrap several plots in a grid, often an uneven number, so there'll often be an "empty spot". I need to use arrangeGrob() -- not grid.arrange() -- because I want to save the plot for later, not plot() it right away.

This works fine, but oddly, arrangeGrob() leaves some weird background in the empty spots.

Like so:

library(ggplot2)
p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()
p2 <- ggplot(mtcars, aes(x=factor(cyl), y=wt)) + geom_boxplot()
p3 <- ggplot(mtcars, aes(x =factor(cyl), y=disp)) + geom_boxplot()
library(gridExtra)
y <- arrangeGrob(p1, p2, p3, ncol = 2)
plot(y)

yields a plot with some weird gray stuff in the bottom right corner:

Compare this to grid.arrange():

grid.arrange(p1, p2, p3, ncol = 2)

yields a pretty plot with no grey weirdness:

Where does this gray stuff in the bottom right corner come from? And how do I get rid of it?

Notice that I cannot avoid the empty spots by changing ncol; I sometimes have an uneven number of plots, so there'll always be empty spots. I'm ok with empty spots, I just like them to be clean. (In isolation, that last sentence sounds pretty OCD-ish.


UPDATE

The package author (?) answered below: I should have used grid.draw(y).

A similar problem remains (maybe the same root cause?): if you plot some object before, the "empty spot" remains occupied by that past plot. Weird. Like so:

plot(p1)
grid.draw(y)

yields:


回答1:


arrangeGrob() now returns a gtable, which you should draw with grid.draw(), not plot().

grid.draw(y)

yields

To get rid of artefacts from past plots (as per above update) use grid.newpage().




回答2:


Remove the nrow argument. Like so:

library(ggplot2)
p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()
p2 <- ggplot(mtcars, aes(x=factor(cyl), y=wt)) + geom_boxplot()
library(gridExtra)
y <- arrangeGrob(p1, p2, ncol = 2)
plot(y)


来源:https://stackoverflow.com/questions/31463445/how-do-i-get-rid-of-random-background-grid-from-arrangegrob

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