Title: | Unified Handling of Graphics Devices |
---|---|
Description: | Functions for creating plots and image files in a unified way regardless of output format (EPS, PDF, PNG, SVG, TIFF, WMF, etc.). Default device options as well as scales and aspect ratios are controlled in a uniform way across all device types. Switching output format requires minimal changes in code. This package is ideal for large-scale batch processing, because it will never leave open graphics devices or incomplete image files behind, even on errors or user interrupts. |
Authors: | Henrik Bengtsson [aut, cre, cph] |
Maintainer: | Henrik Bengtsson <[email protected]> |
License: | LGPL (>= 2.1) |
Version: | 2.17.2 |
Built: | 2024-12-24 03:27:37 UTC |
Source: | https://github.com/HenrikBengtsson/R.devices |
Functions for creating plots and image files in a unified way regardless of output format (EPS, PDF, PNG, SVG, TIFF, WMF, etc.). Default device options as well as scales and aspect ratios are controlled in a uniform way across all device types. Switching output format requires minimal changes in code. This package is ideal for large-scale batch processing, because it will never leave open graphics devices or incomplete image files behind, even on errors or user interrupts.
Vignette 'R.devices overview'
toEPS
(), toPDF
(), toPNG
(), ... - evaluate
graphics code and atomically save plot to a figure file.
To cite this package, please use:
@Manual{, title = {R.devices: Unified Handling of Graphics Devices}, author = {Henrik Bengtsson}, year = {2024}, note = {R package version 2.17.2, https://github.com/HenrikBengtsson/R.devices}, url = {https://henrikbengtsson.github.io/R.devices/}, }
LGPL (>= 2.1).
Henrik Bengtsson [aut, cre, cph].
Get the architecture of an object or coerce it into another
architecture(x, ...) as.architecture( x, ostype = .Platform$OS.type, arch = R.version$arch, ptrsize = .Machine$sizeof.pointer, endian = .Platform$endian, ... )
architecture(x, ...) as.architecture( x, ostype = .Platform$OS.type, arch = R.version$arch, ptrsize = .Machine$sizeof.pointer, endian = .Platform$endian, ... )
x |
The object to be coerced. |
... |
(optional) Additional arguments passed to the underlying method. |
ostype |
A character string, e.g. |
arch |
A character string, e.g. |
ptrsize |
The target pointer size - either |
endian |
The target endianess - either |
architecture()
returns a named list with
character element ostype
and arch
,
integer element ptrsize
, and character element endian
.
These elements take a missing values if they could not be inferred.
as.architecture()
returns a coerced version of x
.
If no coercion was needed, then x
itself is returned.
Captures a plot such that it can be redrawn later/elsewhere.
This feature is only supported in R (>= 3.3.0).
capturePlot(expr, envir=parent.frame(), type=nulldev, ...)
capturePlot(expr, envir=parent.frame(), type=nulldev, ...)
expr |
The |
envir |
The |
type |
The type of graphics device used in the background. The choice should not matter since the result should be identical regardless. All graphics is captured but any output is also voided by sending the output to a "null" file. |
... |
Additional arguments passed to the graphics device. |
Note that plot dimensions/aspect ratios are not recorded. This means that one does not have to worry about those when recording the plot. Instead, they are specified when setting up the graphics device(s) in which the recorded plot is replayed (see example).
Returns a recordedplot
object, which can be
replayPlot()
:ed. If replayed in an
interactive session, the plot is displayed in a new window.
For conveniency, the object is also replayed when print()
:ed.
In order to replay a recordedplot
object, it has to be replayed
on an architecture that is compatible with the one who created the
object.
If this is not the case, then replayPlot()
will generate an Incompatible graphics state error.
The as.architecture()
function of this package tries
to coerce between different architectures, such that one can replay
across architectures using replayPlot(as.architectures(g))
.
For convenience, the recorded plot returned by capturePlot()
is automatically coerced when print()
:ed.
Henrik Bengtsson
[1] Paul Murrell et al.,
Recording and Replaying the Graphics Engine Display List,
December 2015.
https://www.stat.auckland.ac.nz/~paul/Reports/DisplayList/dl-record.html
Internally recordPlot()
is used.
if (getRversion() >= "3.3.0") { oopts <- R.devices::devOptions("*", path=file.path(tempdir(), "figures")) g <- capturePlot({ plot(1:10) }) ## Display print(g) ## Display with a 2/3 height-to-width aspect ratio toDefault(aspectRatio=2/3, { print(g) }) ## Redraw to many output formats using whatever PNG, EPS, and PDF ## device outputs available devEval(c("{png}", "{eps}", "{pdf}"), aspectRatio=2/3, print(g)) R.devices::devOptions("*", path=oopts$path) } ## if (getRversion() >= "3.3.0")
if (getRversion() >= "3.3.0") { oopts <- R.devices::devOptions("*", path=file.path(tempdir(), "figures")) g <- capturePlot({ plot(1:10) }) ## Display print(g) ## Display with a 2/3 height-to-width aspect ratio toDefault(aspectRatio=2/3, { print(g) }) ## Redraw to many output formats using whatever PNG, EPS, and PDF ## device outputs available devEval(c("{png}", "{eps}", "{pdf}"), aspectRatio=2/3, print(g)) R.devices::devOptions("*", path=oopts$path) } ## if (getRversion() >= "3.3.0")
Closes zero or more open devices except screen (interactive) devices.
devDone(which=dev.cur(), ...)
devDone(which=dev.cur(), ...)
which |
|
... |
Not used. |
Returns (invisibly) dev.cur()
.
Henrik Bengtsson
Opens a new graphics device, evaluate (graphing) code, and closes device.
devEval(type=getOption("device"), expr, initially=NULL, finally=NULL, envir=parent.frame(), name=NULL, tags=NULL, sep=getDevOption(type, "sep", default = ","), ..., ext=NULL, filename=NULL, path=getDevOption(type, "path", default = "figures"), field=getDevOption(type, name = "field"), onIncomplete=c("remove", "rename", "keep"), force=getDevOption(type, "force", default = TRUE), which=dev.cur(), .exprAsIs=FALSE, .allowUnknownArgs=FALSE)
devEval(type=getOption("device"), expr, initially=NULL, finally=NULL, envir=parent.frame(), name=NULL, tags=NULL, sep=getDevOption(type, "sep", default = ","), ..., ext=NULL, filename=NULL, path=getDevOption(type, "path", default = "figures"), field=getDevOption(type, name = "field"), onIncomplete=c("remove", "rename", "keep"), force=getDevOption(type, "force", default = TRUE), which=dev.cur(), .exprAsIs=FALSE, .allowUnknownArgs=FALSE)
type |
Specifies the type of graphics device to be used.
The device is created and opened using |
expr |
The |
initially , finally
|
Optional |
envir |
The |
name , tags , sep
|
The fullname name of the image is specified
as the name with optional |
ext |
The filename extension of the image file generated, if any.
By default, it is inferred from argument |
... |
Additional arguments passed to |
filename |
The filename of the image saved, if any.
By default, it is composed of arguments |
path |
The directory where then image should be saved, if any. |
field |
An optional |
onIncomplete |
A |
force |
If |
which |
A |
.exprAsIs , .allowUnknownArgs
|
(Internal use only). |
Returns a DevEvalFileProduct
if the device generated an
image file, otherwise an DevEvalProduct
.
If argument field
is given, then the field of the
DevEvalProduct
is returned instead.
Note that the default return value may be changed in future releases.
If created, the generated image file is saved in the directory
specified by argument path
with a filename consisting of
the name
followed by optional comma-separated tags
and a filename extension given by argument ext
.
By default, the image file is only created if the expr
is evaluated completely. If it is, for instance, interrupted
by the user or due to an error, then any incomplete/blank image
file that was created will be removed. This behavior can be
turned of using argument onIncomplete
.
Henrik Bengtsson
To change default device parameters such as the width or the height,
devOptions
().
devNew
().
# Plot to PNG using one whatever PNG device driver is available res <- devEval("{png}", name="MyPlot", tags=c("10", "rnd"), aspectRatio=0.7, { plot(1:10) }) print(res$pathname) # [1] "figures/MyPlot,10,rnd.png" str(res$dataURI) # chr "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAA..." ## Plot to PDF using grDevices::pdf() res <- devEval("pdf", name="MyPlot", tags=c("10", "rnd"), aspectRatio=0.7, { plot(1:10) }) print(res$pathname) # [1] "figures/MyPlot,10,rnd.pdf" ## Plot to EPS using R.devices::eps() res <- devEval("eps", name="MyPlot", tags=c("10", "rnd"), aspectRatio=0.7, { plot(1:10) }) print(res$pathname) # [1] "figures/MyPlot,10,rnd.eps"
# Plot to PNG using one whatever PNG device driver is available res <- devEval("{png}", name="MyPlot", tags=c("10", "rnd"), aspectRatio=0.7, { plot(1:10) }) print(res$pathname) # [1] "figures/MyPlot,10,rnd.png" str(res$dataURI) # chr "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAA..." ## Plot to PDF using grDevices::pdf() res <- devEval("pdf", name="MyPlot", tags=c("10", "rnd"), aspectRatio=0.7, { plot(1:10) }) print(res$pathname) # [1] "figures/MyPlot,10,rnd.pdf" ## Plot to EPS using R.devices::eps() res <- devEval("eps", name="MyPlot", tags=c("10", "rnd"), aspectRatio=0.7, { plot(1:10) }) print(res$pathname) # [1] "figures/MyPlot,10,rnd.eps"
Gets the labels of zero or more devices.
devGetLabel(which=dev.cur(), ...)
devGetLabel(which=dev.cur(), ...)
which |
|
... |
Not used. |
Returns a character
vector
.
If a device does not exist, an error is thrown.
Henrik Bengtsson
devSetLabel
() and devList
().
Checks whether a device type is interactive or not.
devIsInteractive(types, ...)
devIsInteractive(types, ...)
types |
|
... |
Not used. |
Returns a logical
vector
with TRUE
if the device type is interactive,
otherwise FALSE
.
Henrik Bengtsson
Internally, deviceIsInteractive
is used.
Checks if zero or more devices are open or not.
devIsOpen(which=dev.cur(), ...)
devIsOpen(which=dev.cur(), ...)
which |
|
... |
Not used. |
Returns a named logical
vector
with TRUE
if a device is open,
otherwise FALSE
.
Henrik Bengtsson
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Use devices for conditional processing of code. # Close devices to rerun code. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("Currently opened device:\n") print(devList()) # Alt A: Use device index counter (starting with the 16:th) fig <- 15 if (!devIsOpen(fig <- fig + 1)) { devSet(fig) cat("Figure", fig, "\n") plot(1:10) } cat("Currently opened device:\n") print(devList()) if (!devIsOpen(fig <- fig + 1)) { devSet(fig) cat("Figure", fig, "\n") plot(1:10) } cat("Currently opened device:\n") print(devList()) # Alt B: Use device labels if (!devIsOpen(label <- "part 1")) { devSet(label) cat("Part 1\n") plot(1:10) } cat("Currently opened device:\n") print(devList()) if (!devIsOpen(label <- "part 2")) { devSet(label) cat("Part 2\n") plot(1:10) } cat("Currently opened device:\n") print(devList())
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Use devices for conditional processing of code. # Close devices to rerun code. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cat("Currently opened device:\n") print(devList()) # Alt A: Use device index counter (starting with the 16:th) fig <- 15 if (!devIsOpen(fig <- fig + 1)) { devSet(fig) cat("Figure", fig, "\n") plot(1:10) } cat("Currently opened device:\n") print(devList()) if (!devIsOpen(fig <- fig + 1)) { devSet(fig) cat("Figure", fig, "\n") plot(1:10) } cat("Currently opened device:\n") print(devList()) # Alt B: Use device labels if (!devIsOpen(label <- "part 1")) { devSet(label) cat("Part 1\n") plot(1:10) } cat("Currently opened device:\n") print(devList()) if (!devIsOpen(label <- "part 2")) { devSet(label) cat("Part 2\n") plot(1:10) } cat("Currently opened device:\n") print(devList())
Lists the indices of the open devices named by their labels.
devList(interactiveOnly=FALSE, dropNull=TRUE, ...)
devList(interactiveOnly=FALSE, dropNull=TRUE, ...)
interactiveOnly |
If |
dropNull |
If |
... |
Not used. |
Returns a named integer
vector
.
Henrik Bengtsson
dev.list()
.
Opens a new device.
devNew(type=getOption("device"), ..., scale=1, aspectRatio=1, par=NULL, label=NULL)
devNew(type=getOption("device"), ..., scale=1, aspectRatio=1, par=NULL, label=NULL)
type |
A |
... |
Additional arguments passed to the device |
scale |
A |
aspectRatio |
A |
par |
An optional named |
label |
An optional |
Returns the device index of the opened device.
The default width and height of the generated image is specific to
the type of device used. There is not straightforward programmatic
way to infer these defaults; here we use devOptions
(), which
in most cases returns the correct defaults.
The aspect ratio of an image is the height relative to the width.
If argument height
is not given (or NULL
), it is
calculated as aspectRatio*width
as long as they are given.
Likewise, if argument width
is not given (or NULL
), it is
calculated as width/aspectRatio
as long as they are given.
If neither width
nor height
is given, then width
defaults to devOptions(type)$width
.
If both width
and height
are given, then
aspectRatio
is ignored.
Henrik Bengtsson
devDone
() and devOff
().
For simplified generation of image files, see devEval
().
Closes zero or more devices.
devOff(which=dev.cur(), ...)
devOff(which=dev.cur(), ...)
which |
|
... |
Not used. |
Returns dev.cur()
.
Henrik Bengtsson
devDone
().
Internally, dev.off()
is used.
Gets the default device options as given by predefined devices options adjusted for the default arguments of the device function.
devOptions(type=NULL, custom=TRUE, special=TRUE, inherits=FALSE, drop=TRUE, options=list(), ..., reset=FALSE)
devOptions(type=NULL, custom=TRUE, special=TRUE, inherits=FALSE, drop=TRUE, options=list(), ..., reset=FALSE)
type |
A |
custom |
If |
special |
A |
inherits |
If |
drop |
If |
options |
Optional named |
... |
Optional named arguments for setting new defaults. For more details, see below. |
reset |
If |
If argument special
is TRUE
, then the 'width' and 'height'
options are adjusted according to the rules explained for
argument 'paper' in pdf
, postscript
,
and xfig
.
If drop=TRUE
and a single device is queries, a named list
is
returned, otherwise a matrix
is returned.
If a requested device is not implemented/supported on the current system,
then "empty" results are returned.
If options were set, that is, if named options were specified via
...
, then the list is returned invisibly, otherwise not.
When setting device options, the getOption("devOptions")[[type]]
option is modified. This means that for such options to be effective,
any device function needs to query also such options, which for instance
is done by devNew
().
Also, for certain devices (eps, pdf, postscript, quartz, windows and x11), builtin R device options are set.
Henrik Bengtsson
# Tabulate some of the default settings for known devices print(devOptions()[,c("width", "height", "bg", "fg", "pointsize")])
# Tabulate some of the default settings for known devices print(devOptions()[,c("width", "height", "bg", "fg", "pointsize")])
Activates a device.
devSet(which=dev.next(), ...)
devSet(which=dev.next(), ...)
which |
An index ( |
... |
Not used. |
Returns what dev.set()
returns.
Henrik Bengtsson
devOff
() and devDone
().
Internally, dev.set()
is used.
Sets the label of a device.
devSetLabel(which=dev.cur(), label, ...)
devSetLabel(which=dev.cur(), label, ...)
which |
|
label |
A |
... |
Not used. |
Returns nothing.
Henrik Bengtsson
devGetLabel
() and devList
().
Methods for creating image files of a specific format.
toBMP(name, ...) toPDF(name, ...) toPNG(name, ...) toSVG(name, ...) toTIFF(name, ...) toEMF(name, ..., ext="emf") toWMF(name, ..., ext="wmf") toFavicon(..., name="favicon", ext="png", field=getDevOption("favicon", "field", default="htmlscript")) toDefault(name, ...) toQuartz(name, ...) toX11(name, ...) toWindows(name, ...) toCairoWin(name, ...) toCairoX11(name, ...) toRStudioGD(name, ..., .allowUnknownArgs = TRUE)
toBMP(name, ...) toPDF(name, ...) toPNG(name, ...) toSVG(name, ...) toTIFF(name, ...) toEMF(name, ..., ext="emf") toWMF(name, ..., ext="wmf") toFavicon(..., name="favicon", ext="png", field=getDevOption("favicon", "field", default="htmlscript")) toDefault(name, ...) toQuartz(name, ...) toX11(name, ...) toWindows(name, ...) toCairoWin(name, ...) toCairoX11(name, ...) toRStudioGD(name, ..., .allowUnknownArgs = TRUE)
name |
A |
... , .allowUnknownArgs
|
Additional arguments passed to |
ext , field
|
Passed to |
Returns by default the DevEvalProduct
.
For toFavicon()
the default return value is a character
string.
Both toEMF()
and toWMF()
use the exact same graphics
device (win.metafile()
) and settings. They only differ by
filename extension. The win.metafile()
device function exists
on Windows only; see the grDevices package for more details.
Henrik Bengtsson
These functions are wrappers for devEval
().
See devOptions
() to change the default dimensions for
a specific device type.
Evaluate an R expression with graphical parameters set temporarily.
withPar(expr, ..., args=list(), envir=parent.frame())
withPar(expr, ..., args=list(), envir=parent.frame())
expr |
The R expression to be evaluated. |
... |
Named options to be used. |
args |
(optional) Additional named options specified as a named |
envir |
The |
Upon exit (also on errors), this function will reset all
(modifiable) graphical parameters to the state of options available
upon entry. This means any parameters modified from evaluating
expr
will also be undone upon exit.
Returns the results of the expression evaluated.
Henrik Bengtsson
Internally, eval
() is used to evaluate the expression,
and par
to set graphical parameters.
withPar({ layout(1:4) withPar({ plot(1:10) plot(10:1) }, pch=4) withPar({ plot(1:10) plot(10:1) }, pch=0, bg="yellow") }, mar=c(2,2,1,1))
withPar({ layout(1:4) withPar({ plot(1:10) plot(10:1) }, pch=4) withPar({ plot(1:10) plot(10:1) }, pch=0, bg="yellow") }, mar=c(2,2,1,1))