how do I get rid of random background grid from ar

2019-05-10 05:09发布

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:

grey weirdness

Compare this to grid.arrange():

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

yields a pretty plot with no grey weirdness:

enter image description here

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:

past plot weirdness

2条回答
叼着烟拽天下
2楼-- · 2019-05-10 05:35

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

grid.draw(y)

yields

fine plot

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

查看更多
叛逆
3楼-- · 2019-05-10 05:57

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