Is it possible to plot a graph into several output devices at once? I tried:
getwd()
pdf("level1.pdf")
  pdf("level2.pdf")
    png("level3.png")
    x=1:10
    y=1:10
    plot(x, y)
    dev.off() # close level3
  dev.off() # close level2
  a=10:20
  b=-10:0
  plot(a,b)
dev.off() # close level1
The XY plot goes only into level3.png. (I should go into all 3 files)
Strangely, the AB plot goes into level2.pdf, whie I expected it to be written to level1.pdf, since level2.pdf should be already closed?
It is possible to have more than one device open at the same time, *but only one device is currently “active” and all graphics output is sent to that device. So No, you can't plot a graph into several output devices at once (in parallel/same time I mean). here I detail some handy functions of the device class that you can use.
You can use the functions :
dev.List(): t get list of open devicesdev.cur() to get the current active devicedev.set() to change the active devicedev.next() and dev.prev(): to make the next/previous device on the device listFor example:
pdf("level1.pdf")
pdf("level2.pdf")
png("level3.png")
## list the devices
dev.list()
       pdf            pdf png:level3.png 
         2              3              4 
## current device 
dev.cur()
png:level3.png         ## that's why The XY plot goes only into this device
                 4 
### this will go in the current device
x=1:10
y=1:10
plot(x, y)
## change the active device
dev.set(dev.next())
pdf 
  2 
### close all devices
graphics.off()
## list the devices
dev.list()
NULL
So applying this on your example:
pdf("level1.pdf")
pdf("level2.pdf")
png("level3.png")
dev.off() # close level3
dev.off() # close level2
dev.cur()
pdf           ## plot A,B goes on this device
  3 
                        With ggplot2 you can assign plot objects to variables and print them several times:
library(ggplot2)
p <- ggplot(data.frame(x=1:10, y=1:10), aes(x=x, y=y)) + geom_point()
pdf('a.pdf')
print(p)
dev.off()
png('b.png')
print(p)
dev.off()
Or, with ggsave (thanks to Roland; however, this opens a dummy window on my system -- Ubuntu):
ggsave('a.pdf', p)
ggsave('b.png', p)
Not sure about "regular" plots, I'm using ggplot2 whenever I can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With