Nesting output devices in R?
Asked Answered
S

2

5

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?

Sacttler answered 26/2, 2013 at 8:30 Comment(0)
T
4

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 devices
  • dev.cur() to get the current active device
  • dev.set() to change the active device
  • dev.next() and dev.prev(): to make the next/previous device on the device list

For 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 
Torus answered 26/2, 2013 at 8:50 Comment(0)
A
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.

Argal answered 26/2, 2013 at 8:47 Comment(1)
Function ggsave is even more convenient.Hillier

© 2022 - 2024 — McMap. All rights reserved.