25

I am trying to export a simple plot in .png with transparent background. I am able to export it, but the background stays white.

Mock example

x = c(1, 2, 3)

I've tried this

plot (x)

dev.copy (png,'myplot.png', bg = 'transparent')
dev.off()

And this

plot (x, bg = 'transparent')

dev.copy (png,'myplot.png')
dev.off()

But neither work.

Can someone help?

zx8754
  • 52,746
  • 12
  • 114
  • 209
francoiskroll
  • 1,026
  • 3
  • 13
  • 24
  • 2
    try: `png("myplot.png", width=600, height=400, bg = "transparent"); plot(x); dev.off()` – Adam Quek Apr 25 '17 at 15:26
  • 1
    It worked for me with `plot (x, bg = 'transparent'); dev.copy (png,'myplot.png', bg = 'transparent') ` – G5W Apr 25 '17 at 15:29

2 Answers2

33
x = c(1, 2, 3)
par(bg=NA)
plot (x)

dev.copy(png,'myplot.png')
dev.off()
gonzalez.ivan90
  • 1,322
  • 1
  • 12
  • 22
  • 1
    and how would one revert the `par` change? – Fawwaz Yusran Sep 01 '18 at 02:07
  • 2
    Creating an object with default parametrs: ´parOrig <- par()´ and using it as an ´par()´ argument: ´par(parOrig)´ ´parOrig <- par(); par(bg=NA, mfrow = c(2, 1)); plot (1:3); par(parOrig); plot (1:3)´ – gonzalez.ivan90 Sep 03 '18 at 14:46
1

Instead of saving all parameters, it is better to only save the old value of the parameter that was changed in a call to ´par´ by saving result of ´par´ as in the modified example:

x = c(1, 2, 3)
old.par <- par(bg=NA)
plot (x)

dev.copy(png,'myplot.png')
dev.off()
par(old.par)