patchwork icon indicating copy to clipboard operation
patchwork copied to clipboard

Plots are randomly clipped when saving using png() or ggsave()

Open mw55309 opened this issue 4 years ago • 2 comments

Hi

I am using patchwork to combine together a bunch of ggplots and base R plots. It all seems to work fine, except when I try and save the plot to a file using ggsave() or png()

Here is some code:

layout <- '
ABC
DEF
G##
'

p1 <- ~{plot(1:10)}

png("test.png", width=1200, height=1200)
wrap_plots(
	A=wrap_elements(panel = p1, clip = FALSE),
	B=wrap_elements(panel = p1, clip = FALSE),
	C=wrap_elements(panel = p1, clip = FALSE),	
        D=wrap_elements(panel = p1, clip = FALSE),
	E=wrap_elements(panel = p1, clip = FALSE),
	F=wrap_elements(panel = p1, clip = FALSE),
	G=wrap_elements(panel = p1, clip = FALSE),
design=layout)
dev.off()

The result is this image where you can see A, B, C and D all have their bottom and/or right sections clipped.

What's happening here?

test

mw55309 avatar Jul 09 '21 10:07 mw55309

Here is a ggsave example (which apart from looking terrible, also contains right-clipped plots)




layout <- '
ABC
DEF
G##
'

p1 <- ~{plot(1:10)}

ggsave(
wrap_plots(
	A=wrap_elements(panel = p1, clip = FALSE),
	B=wrap_elements(panel = p1, clip = FALSE),
	C=wrap_elements(panel = p1, clip = FALSE),
	D=wrap_elements(panel = p1, clip = FALSE),
	E=wrap_elements(panel = p1, clip = FALSE),
	F=wrap_elements(panel = p1, clip = FALSE),
	G=wrap_elements(panel = p1, clip = FALSE),
design=layout),
filename="test.gg.png", units="cm", width=20, height=20)

test gg

mw55309 avatar Jul 09 '21 10:07 mw55309

In this particular example, I think it's the clip = FALSE part of your argument, so each plot takes up more space than it actually needs, and then overlaps the others.

In this example, I can get rid of the overlap by changing clip = TRUE.

layout <- '
ABC
DEF
G##
'

p1 <- ~{plot(1:10)}

library(patchwork)

png("test.png", width=1200, height=1200)
wrap_plots(
  A=wrap_elements(panel = p1, clip = TRUE),
  B=wrap_elements(panel = p1, clip = TRUE),
  C=wrap_elements(panel = p1, clip = TRUE),
  D=wrap_elements(panel = p1, clip = TRUE),
  E=wrap_elements(panel = p1, clip = TRUE),
  F=wrap_elements(panel = p1, clip = TRUE),
  G=wrap_elements(panel = p1, clip = TRUE),
  design=layout)
dev.off()

test

I will note that in other cases when one is combining multiple ggplot2 things together, you might need to add coord_*(clip = "off") or you may see similar effects as this, for similar reasons.

rmflight avatar Jul 09 '21 12:07 rmflight