The R Graphics Devices and Support for Colours and Fonts

The R Graphics Devices and Support for Colours and Fonts [R logo]

Help pages for package `grDevices' version 2.4.1

grDevices-package | The R Graphics Devices and Support for Colours and Fonts
.ps.prolog | PostScript Graphics
bitmap | Graphics Device for Bitmap Files via GhostScript
bmp | BMP, JPEG and PNG graphics devices
boxplot.stats | Box Plot Statistics
bringToTop | Assign Focus to a Window
check.options | Set Options with Consistency Checks
chull | Compute Convex Hull of a Set of Points
CIDFont | Type 1 and CID Fonts
cm | Unit tansformation
cm.colors | Color Palettes
col2rgb | Color to RGB Conversion
colorConverter | Create colour spaces
colorRamp | Color interpolation
colorRampPalette | Color interpolation
colors | Color Names
colorspaces | Convert between colour spaces
colours | Color Names
contourLines | Calculate Contour Lines
convertColor | Convert between colour spaces
dev.control | Copy Graphics Between Multiple Devices
dev.copy | Copy Graphics Between Multiple Devices
dev.copy2eps | Copy Graphics Between Multiple Devices
dev.cur | Control Multiple Devices
dev.interactive | Is the Current Graphics Device Interactive ?
dev.list | Control Multiple Devices
dev.next | Control Multiple Devices
dev.off | Control Multiple Devices
dev.prev | Control Multiple Devices
dev.print | Copy Graphics Between Multiple Devices
dev.set | Control Multiple Devices
dev2bitmap | Graphics Device for Bitmap Files via GhostScript
device | List of Graphical Devices
Devices | List of Graphical Devices
embedFonts | Embed Fonts in PostScript and PDF
extendrange | Extend a Numerical Range by a Small Percentage
getGraphicsEvent | Wait for a mouse or keyboard event from a graphics window
graphics.off | Control Multiple Devices
gray | Gray Level Specification
gray.colors | Gray Color Palette
grDevices | The R Graphics Devices and Support for Colours and Fonts
grey | Gray Level Specification
grey.colors | Gray Color Palette
hcl | HCL Color Specification
heat.colors | Color Palettes
Hershey | Hershey Vector Fonts in R
hsv | HSV Color Specification
Japanese | Japanese characters in R
jpeg | BMP, JPEG and PNG graphics devices
make.rgb | Create colour spaces
n2mfrow | Compute Default mfrow From Number of Plots
nclass.FD | Compute the Number of Classes for a Histogram
nclass.scott | Compute the Number of Classes for a Histogram
nclass.Sturges | Compute the Number of Classes for a Histogram
palette | Set or View the Graphics Palette
pdf | PDF Graphics Device
pdfFonts | PostScript and PDF Font Families
pictex | A PicTeX Graphics Driver
plotmath | Mathematical Annotation in R
png | BMP, JPEG and PNG graphics devices
postscript | PostScript Graphics
postscriptFonts | PostScript and PDF Font Families
print.recordedplot | Record and Replay Plots
print.SavedPlots | Windows graphics devices
ps.options | Auxiliary Function to Set/View Argument of postscript
rainbow | Color Palettes
recordGraphics | Record graphics operations
recordPlot | Record and Replay Plots
replayPlot | Record and Replay Plots
rgb | RGB Color Specification
rgb2hsv | RGB to HSV Conversion
savePlot | Save Windows Plot to a File
stayOnTop | Assign Focus to a Window
terrain.colors | Color Palettes
topo.colors | Color Palettes
trans3d | 3D to 2D Transformation for Perspective Plots
Type1Font | Type 1 and CID Fonts
win.graph | Windows graphics devices
win.metafile | Windows graphics devices
win.print | Windows graphics devices
windows | Windows graphics devices
windowsFont | Windows Fonts
windowsFonts | Windows Fonts
X11 | Windows graphics devices
x11 | Windows graphics devices
xfig | XFig Graphics Device
xy.coords | Extracting Plotting Structures
xyz.coords | Extracting Plotting Structures
[.SavedPlots | Windows graphics devices


Box Plot Statistics

Description

This function is typically called by another function to gather the statistics necessary for producing box plots, but may be invoked separately.

Usage

boxplot.stats(x, coef = 1.5, do.conf = TRUE, do.out = TRUE)

Arguments

x | a numeric vector for which the boxplot will be constructed (NAs and NaNs are allowed and omitted).
coef | this determines how far the plot “whiskers” extend out from the box. If coef is positive, the whiskers extend to the most extreme data point which is no more than coef times the length of the box away from the box. A value of zero causes the whiskers to extend to the data extremes (and no outliers be returned).
do.conf,do.out | logicals; if FALSE, the conf or out component respectively will be empty in the result.

Details

The two “hinges” are versions of the first and third quartile, i.e., close to quantile(x, c(1,3)/4). The hinges equal the quartiles for odd n (where n <- length(x)) and differ for even n. Where the quartiles only equal observations for n %% 4 == 1 (n = 1 mod 4), the hinges do so additionally for n %% 4 == 2 (n = 2 mod 4), and are in the middle of two observations otherwise.

The notches (if requested) extend to +/-1.58 IQR/sqrt(n). This seems to be based on same calculations as the formula with 1.57 in Chambers et al. (1983, p. 62), given in McGill et al. (1978, p. 16). They are based on asymptotic normality of the median and roughly equal sample sizes for the two medians being compared, and are said to be rather insensitive to the underlying distributions of the samples. The idea appears to be to give roughly a 95% confidence interval for the difference in two medians.

Value

List with named components as follows:

stats | a vector of length 5, containing the extreme of the lower whisker, the lower “hinge”, the median, the upper “hinge” and the extreme of the upper whisker.
n | the number of non-NA observations in the sample.
conf | the lower and upper extremes of the “notch” (if(do.conf)). See the details.
out | the values of any data points which lie beyond the extremes of the whiskers (if(do.out)).

Note that $stats and $conf are sorted in increasing order, unlike S, and that $n and $out include any +- Inf values.

References

Tukey, J. W. (1977) Exploratory Data Analysis. Section 2C.

McGill, R., Tukey, J. W. and Larsen, W. A. (1978) Variations of box plots. The American Statistician 32, 12–16.

Velleman, P. F. and Hoaglin, D. C. (1981) Applications, Basics and Computing of Exploratory Data Analysis. Duxbury Press.

Emerson, J. D and Strenio, J. (1983). Boxplots and batch comparison. Chapter 3 of Understanding Robust and Exploratory Data Analysis, eds. D. C. Hoaglin, F. Mosteller and J. W. Tukey. Wiley.

Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983) Graphical Methods for Data Analysis. Wadsworth & Brooks/Cole.

See Also

fivenum, boxplot, bxp.

Examples

x <- c(1:100, 1000)
(b1 <- boxplot.stats(x))
(b2 <- boxplot.stats(x, do.conf=FALSE, do.out=FALSE))
stopifnot(b1 $ stats == b2 $ stats) # do.out=F is still robust
boxplot.stats(x, coef = 3, do.conf=FALSE)
## no outlier treatment:
boxplot.stats(x, coef = 0)

boxplot.stats(c(x, NA)) # slight change : n is 101
(r <- boxplot.stats(c(x, -1:1/0)))
stopifnot(r$out == c(1000, -Inf, Inf))
[Package grDevices version 2.4.1 Index]


Assign Focus to a Window

Description

bringToTop brings the specified screen device's window to the front of the window stack (and gives it focus). With argument -1, it brings the console to the top.

If stay = TRUE, the window is designated as a topmost window, i.e. it will stay on top of any regular window. stay may only be used when Rgui is run in SDI mode. This corresponds to the ``Stay on top'' popup menu item in Rgui.

Usage

bringToTop(which = dev.cur(), stay = FALSE)

Arguments

which | a device number, or -1.
stay | whether to make the window stay on top.

See Also

windows


Set Options with Consistency Checks

Description

Utility function for setting options with some consistency checks. The attributes of the new settings in new are checked for consistency with the model (often default) list in name.opt.

Usage

check.options(new, name.opt, reset = FALSE, assign.opt = FALSE,
              envir = .GlobalEnv,
              check.attributes = c("mode", "length"),
              override.check = FALSE)

Arguments

new | a named list
name.opt | character with the name of R object containing the “model” (default) list.
reset | logical; if TRUE, reset the options from name.opt. If there is more than one R object with name name.opt, remove the first one in the search() path.
assign.opt | logical; if TRUE, assign the ...
envir | the environment used for get and assign.
check.attributes | character containing the attributes which check.options should check.
override.check | logical vector of length length(new) (or 1 which entails recycling). For those new[i] where override.check[i] == TRUE, the checks are overriden and the changes made anyway.

Value

A list of components with the same names as the one called name.opt. The values of the components are changed from the new list, as long as these pass the checks (when these are not overridden according to override.check).

Author(s)

Martin Maechler

See Also

ps.options which uses check.options.

Examples

(L1 <- list(a=1:3, b=pi, ch="CH"))
check.options(list(a=0:2), name.opt = "L1")
check.options(NULL, reset = TRUE, name.opt = "L1")


Compute Convex Hull of a Set of Points

Description

Computes the subset of points which lie on the convex hull of the set of points specified.

Usage

chull(x, y = NULL)

Arguments

x, y coordinate vectors of points. This can be specified as two vectors x and y, a 2-column matrix x, a list x with two components, etc, see xy.coords.

Details

xy.coords is used to interpret the specification of the points. The algorithm is that given by Eddy (1977).

‘Peeling’ as used in the S function chull can be implemented by calling chull recursively.

Value

An integer vector giving the indices of the points lying on the convex hull, in clockwise order.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Eddy, W. F. (1977) A new convex hull algorithm for planar sets. ACM Transactions on Mathematical Software, 3, 398–403.

Eddy, W. F. (1977) Algorithm 523. CONVEX, A new convex hull algorithm for planar sets[Z]. ACM Transactions on Mathematical Software, 3, 411–412.

See Also

xy.coords,polygon

Examples

X <- matrix(rnorm(2000), ncol = 2)
chull(X)
## Not run:
  # Example usage from graphics package
  plot(X, cex = 0.5)
  hpts <- chull(X)
  hpts <- c(hpts, hpts[1])
  lines(X[hpts, ])
## End(Not run)


Unit tansformation

Description

Translates from inches to cm (centimeters).

Usage

cm(x)

Arguments

x numeric vector

Examples

cm(1)# = 2.54


Color to RGB Conversion

Description

“Any R color” to RGB (red/green/blue) conversion.

Usage

col2rgb(col, alpha = FALSE)

Arguments

col | vector of any of the three kind of R colors, i.e., either a color name (an element of colors()), a hexadecimal string of the form "#rrggbb", or an integer i meaning palette()[i].
alpha | logical value indicating whether alpha channel values should be returned.

Details

For integer colors, 0 is shorthand for the current par("bg"), and NA means “nothing” which effectively does not draw the corresponding item.

For character colors, "NA" is equivalent to NA above.

Value

an integer matrix with three or four rows and number of columns the length (and names if any) as col.

Author(s)

Martin Maechler

See Also

rgb, colors, palette, etc.

Examples

col2rgb("peachpuff")
col2rgb(c(blu = "royalblue", reddish = "tomato")) # names kept

col2rgb(1:8)# the ones from the palette() :

col2rgb(paste("gold", 1:4, sep=""))

col2rgb("#08a0ff")
## all three kind of colors mixed :
col2rgb(c(red="red", palette= 1:3, hex="#abcdef"))

##-- NON-INTRODUCTORY examples --

grC <- col2rgb(paste("gray",0:100,sep=""))
table(print(diff(grC["red",])))# '2' or '3': almost equidistant
## The 'named' grays are in between {"slate gray" is not gray, strictly}
col2rgb(c(g66="gray66", darkg= "dark gray", g67="gray67",
          g74="gray74", gray =      "gray", g75="gray75",
          g82="gray82", light="light gray", g83="gray83"))

crgb <- col2rgb(cc <- colors())
colnames(crgb) <- cc
t(crgb)## The whole table

ccodes <- c(256^(2:0) %*% crgb)## = internal codes
## How many names are 'aliases' of each other:
table(tcc <- table(ccodes))
length(uc <- unique(sort(ccodes))) # 502
## All the multiply named colors:
mult <- uc[tcc >= 2]
cl <- lapply(mult, function(m) cc[ccodes == m])
names(cl) <- apply(col2rgb(sapply(cl, function(x)x[1])),
                   2, function(n)paste(n, collapse=","))
utils::str(cl)
## Not run:
 if(require(xgobi)) { ## Look at the color cube dynamically :
   tc <- t(crgb[, !duplicated(ccodes)])
   table(is.gray <- tc[,1] == tc[,2] & tc[,2] == tc[,3])# (397, 105)
   xgobi(tc, color = c("gold", "gray")[1 + is.gray])
 }
## End(Not run)


Color interpolation

Description

These functions return functions that interpolate a set of given colors to create new color palettes (like topo.colors) and color ramps, functions that map the interval [0, 1] to colors (like grey.

Usage

colorRamp(colors, bias = 1, space = c("rgb", "Lab"),
          interpolate = c("linear", "spline"))
colorRampPalette(colors, ...)

Arguments

colors | Colors to interpolate
bias | A positive number. Higher values give more widely spaced colors at the high end.
space | Interpolation in RGB or CIE Lab color spaces
interpolate | Use spline or linear interpolation.
... | arguments to pass to colorRamp.

Details

The CIE Lab color space is approximately perceptually uniform, and so gives smoother and more uniform color ramps. On the other hand, palettes that vary from one hue to another via white may have a more symmetrical appearance in RGB space.

The conversion formulas in this function do not appear to be completely accurate and the color ramp may not reach the extreme values in Lab space. Future changes in the R color model may change the colors produced with space="Lab".

Value

colorRamp returns a function that maps values between 0 and 1 to colors. colorRampPalette returns a function that takes an integer argument and returns that number of colors interpolating the given sequence (similar to heat.colors or terrain.colors.

See Also

Good starting points for interpolation are the "sequential" and "diverging" ColorBrewer palettes in the RColorBrewer package

Examples

## Here space="rgb" gives palettes that vary only in saturation,
## as intended.
## With space="Lab" the steps are more uniform, but the hues
## are slightly purple.
filled.contour(volcano,
               color = colorRampPalette(c("red", "white", "blue")),
               asp = 1)
filled.contour(volcano,
               color = colorRampPalette(c("red", "white", "blue"),
                                        space = "Lab"),
               asp = 1)

## Interpolating a 'sequential' ColorBrewer palette
YlOrBr <- c("#FFFFD4", "#FED98E", "#FE9929", "#D95F0E", "#993404")
filled.contour(volcano,
               color = colorRampPalette(YlOrBr, space = "Lab"),
               asp = 1)
filled.contour(volcano,
               color = colorRampPalette(YlOrBr, space = "Lab",
                                        bias = 0.5),
               asp = 1)

## 'jet.colors' is "as in Matlab" (and hurting the eye by oversaturation)
jet.colors <-
  colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan",
                     "#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
filled.contour(volcano, color = jet.colors, asp = 1)

## space="Lab" helps when colors don't form a natural sequence
m <- outer(1:20,1:20,function(x,y) sin(sqrt(x*y)/3))
rgb.palette <- colorRampPalette(c("red", "orange", "blue"),
                                space = "rgb")
Lab.palette <- colorRampPalette(c("red", "orange", "blue"),
                                space = "Lab")
filled.contour(m,col = rgb.palette(20))
filled.contour(m,col = Lab.palette(20))


Color Names

Description

Returns the built-in color names which R knows about.

Usage

colors()
colours()

Details

These color names can be used with a col= specification in graphics functions.

An even wider variety of colors can be created with primitives rgb and hsv or the derived rainbow, heat.colors, etc.

Value

A character vector containing all the built-in color names.

See Also

palette for setting the “palette” of colors for
par(col=<num>);
rgb, hsv, hcl, gray;
rainbow for a nice example;
and heat.colors, topo.colors for images.

col2rgb for translating to RGB numbers and extended examples.

Examples

cl <- colors()
length(cl); cl[1:20]


Calculate Contour Lines

Description

Calculate contour lines for a given set of data.

Usage

contourLines(x = seq(0, 1, len = nrow(z)),
             y = seq(0, 1, len = ncol(z)),
             z, nlevels = 10,
             levels = pretty(range(z, na.rm=TRUE), nlevels))

Arguments

x,y | locations of grid lines at which the values in z are measured. These must be in ascending order. By default, equally spaced values from 0 to 1 are used. If x is a list, its components x$x and x$y are used for x and y, respectively. If the list has component z this is used for z.
z | a matrix containing the values to be plotted (NAs are allowed). Note that x can be used instead of z for convenience.
nlevels | number of contour levels desired iff levels is not supplied.
levels | numeric vector of levels at which to draw contour lines.

Details

contourLines draws nothing, but returns a set of contour lines.

There is currently no documentation about the algorithm. The source code is in ‘$R_HOME/src/main/plot3d.c’.

Value

A list of contours. Each contour is a list with elements:

level | The contour level.
x | The x-coordinates of the contour.
y | The y-coordinates of the contour.

See Also

options("max.countour.segments") for the maximal complexity of a single contour line.

contour.

Examples

x <- 10*1:nrow(volcano)
y <- 10*1:ncol(volcano)
contourLines(x, y, volcano)


Convert between colour spaces

Description

Convert colours between standard colour space representations. This function is experimental.

Usage

convertColor(color, from, to, from.ref.white, to.ref.white,
             scale.in=1, scale.out=1, clip=TRUE)

Arguments

color | A matrix whose rows specify colors
from,to | Input and output color spaces. See Details below
from.ref.white,to.ref.white | Reference whites or NULL if these are built in to the definition, as for RGB spaces. D65 is the default, see Details for others
scale.in, scale.out | Input is divided by scale.in, output is multiplied by scale.out. Use NULL to suppress scaling when input or output is not numeric.
clip | If TRUE, truncate RGB output to [0,1], FALSE return out-of-range RGB, NA set out of range colors to NaN.

Details

Color spaces are specified by objects of class colorConverter, created by colorConverter or make.rgb. Built-in color spaces may be referenced by strings: "XYZ", "sRGB", "Apple RGB", "CIE RGB", "Lab", "Luv". The converters for these colour spaces are in the object colorspaces.

The "sRGB" color space is that used by standard PC monitors. "Apple RGB" is used by Apple monitors. "Lab" and "Luv" are approximately perceptually uniform spaces standardized by the Commission Internationale d'Eclairage. XYZ is a 1931 CIE standard capable of representing all visible colors (and then some), but not in a perceptually uniform way.

The Lab and Luv spaces describe colors of objects, and so require the specification of a reference “white light” color. Illuminant D65 is a standard indirect daylight, Illuminant D50 is close to direct sunlight, and Illuminant A is the light from a standard incandescent bulb. Other standard CIE illuminants supported are B, C, E and D55. RGB colour spaces are defined relative to a particular reference white, and can be only approximately translated to other reference whites. The Bradford chromatic adaptation algorithm is used for this.

The RGB color spaces are specific to a particular class of display. An RGB space cannot represent all colors, and the clip option controls what is done to out-of-range colors.

Value

A 3-row matrix whose columns specify the colors.

References

For all the conversion equations http://www.brucelindbloom.com/

For the white points http://www.efg2.com/Lab/Graphics/Colors/Chromaticity.htm

See Also

col2rgb and colors for ways to specify colors in graphics.

make.rgb for specifying other colour spaces.

Examples

par(mfrow=c(2,2))
## The displayable colors from four planes of Lab space
ab <- expand.grid(a=(-10:15)*10,b=(-15:10)*10)

Lab <- cbind(L=20,ab)
srgb <- convertColor(Lab,from="Lab",to="sRGB",clip=NA)
clipped <- attr(na.omit(srgb),"na.action")
srgb[clipped,] <- 0
cols <- rgb(srgb[,1],srgb[,2],srgb[,3])
image((-10:15)*10,(-15:10)*10,matrix(1:(26*26),ncol=26),col=cols,
  xlab="a",ylab="b",main="Lab: L=20")

Lab <- cbind(L=40,ab)
srgb <- convertColor(Lab,from="Lab",to="sRGB",clip=NA)
clipped <- attr(na.omit(srgb),"na.action")
srgb[clipped,] <- 0
cols <- rgb(srgb[,1],srgb[,2],srgb[,3])
image((-10:15)*10,(-15:10)*10,matrix(1:(26*26),ncol=26),col=cols,
  xlab="a",ylab="b",main="Lab: L=40")

Lab <- cbind(L=60,ab)
srgb <- convertColor(Lab,from="Lab",to="sRGB",clip=NA)
clipped <- attr(na.omit(srgb),"na.action")
srgb[clipped,] <- 0
cols <- rgb(srgb[,1],srgb[,2],srgb[,3])
image((-10:15)*10,(-15:10)*10,matrix(1:(26*26),ncol=26),col=cols,
  xlab="a",ylab="b",main="Lab: L=60")

Lab <- cbind(L=80,ab)
srgb <- convertColor(Lab,from="Lab",to="sRGB",clip=NA)
clipped <- attr(na.omit(srgb),"na.action")
srgb[clipped,] <- 0
cols <- rgb(srgb[,1],srgb[,2],srgb[,3])
image((-10:15)*10,(-15:10)*10,matrix(1:(26*26),ncol=26),col=cols,
  xlab="a",ylab="b",main="Lab: L=80")

(cols <- t(col2rgb(palette())))
(lab <- convertColor(cols,from="sRGB",to="Lab",scale.in=255))
round(convertColor(lab,from="Lab",to="sRGB",scale.out=255))


Control Multiple Devices

Description

These functions provide control over multiple graphics devices.

Only one device is the active device. This is the device in which all graphics operations occur.

Devices are associated with a name (e.g., "X11" or "postscript") and a number; the "null device" is always device 1.

dev.off shuts down the specified (by default the current) device. graphics.off() shuts down all open graphics devices.

dev.set makes the specified device the active device.

Usage

dev.cur()
dev.list()
dev.next(which = dev.cur())
dev.prev(which = dev.cur())
dev.off(which = dev.cur())
dev.set(which = dev.next())
graphics.off()

Arguments

which An integer specifying a device number

Value

dev.cur returns the number and name of the active device, or 1, the null device, if none is active.
dev.list returns the numbers of all open devices, except device 1, the null device. This is a numeric vector with a names attribute giving the names, or NULL is there is no open device.
dev.next and dev.prev return the number and name of the next / previous device in the list of devices. The list is regarded as a circular list, and "null device" will be included only if there are no open devices.
dev.off returns the name and number of the new active device (after the specified device has been shut down).
dev.set returns the name and number of the new active device.

See Also

Devices, such as postscript, etc.

layout and its links for setting up plotting regions on the current device.

Examples

## Not run:
## Unix-specific example
x11()
plot(1:10)
x11()
plot(rnorm(10))
dev.set(dev.prev())
abline(0,1)# through the 1:10 points
dev.set(dev.next())
abline(h=0, col="gray")# for the residual plot
dev.set(dev.prev())
dev.off(); dev.off()#- close the two X devices
## End(Not run)


Copy Graphics Between Multiple Devices

Description

dev.copy copies the graphics contents of the current device to the device specified by which or to a new device which has been created by the function specified by device (it is an error to specify both which and device). (If recording is off on the current device, there are no contents to copy: this will result in no plot or an empty plot.) The device copied to becomes the current device.

dev.print copies the graphics contents of the current device to a new device which has been created by the function specified by device and then shuts the new device.

dev.copy2eps is similar to dev.print but produces an EPSF output file, in portrait orientation (horizontal = FALSE)

dev.control allows the user to control the recording of graphics operations in a device. If displaylist is "inhibit" ("enable") then recording is turned off (on). It is only safe to change this at the beginning of a plot (just before or just after a new page). Initially recording is on for screen devices, and off for print devices.

Usage

dev.copy(device, ..., which = dev.next())
dev.print(device = postscript, ...)
dev.copy2eps(...)
dev.control(displaylist = c("inhibit", "enable"))

Arguments

device | A device function (e.g., x11, postscript, ...)
... | Arguments to the device function above. For dev.print, this includes which and by default any postscript arguments.
which | A device number specifying the device to copy to
displaylist | A character string: the only valid values are "inhibit" and "enable".

Details

For dev.copy2eps, width and height are taken from the current device unless otherwise specified. If just one of width and height is specified, the other is adjusted to preserve the aspect ratio of the device being copied. The default file name is Rplot.eps.

The default for dev.print is to produce and print a postscript copy. This will not work unless options("printcmd") is set suitably and you have a PostScript printer: see postscript for how to set this up. Windows users may prefer to use dev.print(win.print).

dev.print is most useful for producing a postscript print (its default) when the following applies. Unless file is specified, the plot will be printed. Unless width, height and pointsize are specified the plot dimensions will be taken from the current device, shrunk if necessary to fit on the paper. (pointsize is rescaled if the plot is shrunk.) If horizontal is not specified and the plot can be printed at full size by switching its value this is done instead of shrinking the plot region.

If dev.print is used with a specified device (even postscript) it sets the width and height in the same way as dev.copy2eps. This will not be appropriate unless the device specifies dimensions in inches, in particular not for png, jpeg and (Windows only) bmp.

Value

dev.copy returns the name and number of the device which has been copied to.
dev.print and dev.copy2eps return the name and number of the device which has been copied from.

Note

Most devices (including all screen devices) have a display list which records all of the graphics operations that occur in the device. dev.copy copies graphics contents by copying the display list from one device to another device. Also, automatic redrawing of graphics contents following the resizing of a device depends on the contents of the display list.

After the command dev.control("inhibit"), graphics operations are not recorded in the display list so that dev.copy and dev.print will not copy anything and the contents of a device will not be redrawn automatically if the device is resized.

The recording of graphics operations is relatively expensive in terms of memory so the command dev.control("inhibit") can be useful if memory usage is an issue.

See Also

dev.cur and other dev.xxx functions

Examples

## Not run:
x11()
plot(rnorm(10), main="Plot 1")
dev.copy(device=x11)
mtext("Copy 1", 3)
dev.print(width=6, height=6, horizontal=FALSE) # prints it
dev.off(dev.prev())
dev.off()
## End(Not run)


Graphics Device for Bitmap Files via GhostScript

Description

bitmap generates a graphics file. dev2bitmap copies the current graphics device to a file in a graphics format.

Usage

bitmap(file, type = "png256", height = 6, width = 6, res = 72,
       pointsize, ...)

dev2bitmap(file, type = "png256", height = 6, width = 6, res = 72,
           pointsize, ...)

Arguments

file | The output file name, with an appropriate extension.
type | The type of bitmap. the default is "png256".
height | The plot height, in inches.
width | The plot width, in inches.
res | Resolution, in dots per inch.
pointsize | The pointsize to be used for text: defaults to something reasonable given the width and height
... | Other parameters passed to postscript.

Details

dev2bitmap works by copying the current device to a postscript device, and post-processing the output file using ghostscript. bitmap works in the same way using a postscript device and postprocessing the output as “printing”.

You will need a version of ghostscript (5.10 and later have been tested): the full path to the executable can be set by the environment variable R_GSCMD. (If this is unset the command "gswin32c.exe" is used.)

The types available will depend on the version of ghostscript, but are likely to include "pcxmono", "pcxgray", "pcx16", "pcx256", "pcx24b", "pcxcmyk", "pbm", "pbmraw", "pgm", "pgmraw", "pgnm", "pgnmraw", "pnm", "pnmraw", "ppm", "ppmraw", "pkm", "pkmraw", "tiffcrle", "tiffg3", "tiffg32d", "tiffg4", "tifflzw", "tiffpack", "tiff12nc", "tiff24nc", "psmono", "psgray", "psrgb", "bit", "bitrgb", "bitcmyk", "pngmono", "pnggray", "png16", "png256", "png16m", "jpeg", "jpeggray", "pdfwrite".

Note: despite the name of the functions they can produce PDF via type = "pdfwrite", and the PDF produced is not bitmapped.

For formats which contain a single image, a file specification like Rplots%03d.png can be used: this is interpreted by GhostScript.

For dev2bitmap if just one of width and height is specified, the other is chosen to preserve aspect ratio of the device being copied.

Value

None.

Note

Use of bitmap will leave a temporary file (with file name starting Rbit). Use of the pdf, bmp, png and jpeg devices is preferable to using these functions.

See Also

postscript, png and jpeg and on Windows bmp.

pdf generate PDF directly.

To display an array of data, see image.


Is the Current Graphics Device Interactive ?

Description

Test if the current graphics device is interactive.

Usage

dev.interactive(orNone = FALSE)

Arguments

orNone logical; if TRUE, the function also returns TRUE when .Device == "null device" and getOption("device") is among the interactive devices.

Details

The X11 (Unix), windows (Windows) and quartz (MacOS X) are regarded as interactive, together with GTK and gnome (used with the GNOME GUI: GTK is available in package gtkDevice and gnome is expected to be in a package gnomeDevice) and JavaGD (from the JGR project, see http://stats.math.uni-augsburg.de/JGR/).

Value

dev.interactive() returns a logical, TRUE iff an interactive (screen) device is in use.

See Also

Devices for the available devices on your platform.

Examples

dev.interactive # definition -> see list of "interactive" devices explicitly


List of Graphical Devices

Description

The following graphics devices are currently available:

  • windows The graphics driver for Windows (on screen, to printer and to Windows metafile).
  • postscript Writes PostScript graphics commands to a file
  • pdf Write PDF graphics commands to a file
  • pictex Writes LaTeX/PicTeX graphics commands to a file
  • png PNG bitmap device
  • jpeg JPEG bitmap device
  • bmp BMP bitmap device
  • xfig Device for XFIG graphics file format
  • bitmap bitmap pseudo-device via GhostScript (if available).

Details

If no device is open, using a high-level graphics function will cause a device to be opened. Which device is given by options("device") which is initially set as the most appropriate for each platform: a screen device for most interactive use and postscript otherwise. The exception is interactive use under Unix if no screen device is known to be available, when postscript() is used for most systems; pdf() for Mac OS X.

See Also

The individual help files for further information on any of the devices listed here;

dev.interactive, dev.cur, dev.print, graphics.off, image, dev2bitmap.

Examples

## Not run:
## open the default screen device on this platform if no device is
## open
if(dev.cur() == 1) get(getOption("device"))()
## End(Not run)


Embed Fonts in PostScript and PDF

Description

Runs ghostscript to process a PDF or PostScript file and embed all fonts in the file.

Usage

embedFonts(file, format, outfile = file, fontpaths = "", options = "")

Arguments

file | a character string giving the name of the original file.
format | either "pswrite" or "pdfwrite". If not specified, it is guessed from the suffix of file.
outfile | the name of the new file (with fonts embedded).
fontpaths | a character vector giving directories that ghostscript will search for fonts.
options | a character string containing further options to ghostscript.

Details

This function is not necessary if you just use the standard default fonts for PostScript and PDF output.

If you use a special font, this function is useful for embedding that font in your PostScript or PDF document so that it can be shared with others without them having to install your special font.

If the special font is not installed for ghostscript, you will need to tell ghostscript where the font is, using something like options="-sFONTPATH=path/to/font".

This function relies on a suitable ghostscript executable being in your path, or the environment variable R_GSCMD (the same as bitmap) being set as the full path to the ghostscript executable. For Windows users, this should be the path to gswin32c.exe.

Value

The shell command used to invoke ghostscript is returned invisibly. This may be useful for debugging purposes as you can run the command by hand in a shell to look for problems.

See Also

postscriptFonts, Devices.


Extend a Numerical Range by a Small Percentage

Description

Extends a numerical range by a small percentage, i.e., fraction, on both sides.

Usage

extendrange(x, r = range(x, na.rm = TRUE), f = 0.05)

Arguments

x | numeric vector; not used if r is specified.
r | numeric vector of length 2; defaults to the range of x.
f | number specifying the fraction by which the range should be extended.

Value

numeric vector of length 2, “r extended”, namely simply r + c(-f,f) * diff(r).

See Also

range; pretty which can be considered a sophisticated extension of extendrange.

Examples

x <- 1:5
(r <- range(x))         # 1    5
extendrange(x)          # 0.8  5.2
extendrange(x, f= 0.01) # 0.96 5.04
## Use 'r' if you have it already:
stopifnot(identical(extendrange(r=r),
                    extendrange(x)))


Wait for a mouse or keyboard event from a graphics window

Description

This function waits for input from a graphics window in the form of a mouse or keyboard event.

Usage

getGraphicsEvent(prompt = "Waiting for input",
                 onMouseDown = NULL, onMouseMove = NULL, onMouseUp = NULL,
                 onKeybd = NULL)

Arguments

prompt | prompt to be displayed to the user
onMouseDown | a function to respond to mouse clicks
onMouseMove | a function to respond to mouse movement
onMouseUp | a function to respond to mouse button releases
onKeybd | a function to respond to key presses

Details

This function allows user input from some graphics devices (currently only the Windows screen display). When called, event handlers may be installed to respond to events involving the mouse or keyboard.

The mouse event handlers should be functions with header function(buttons, x, y). The coordinates x and y will be passed to mouse event handlers in device independent coordinates (i.e. the lower left corner of the window is (0,0), the upper right is (1,1)). The buttons argument will be a vector listing the buttons that are pressed at the time of the event, with 0 for left, 1 for middle, and 2 for right.

The keyboard event handler should be a function with header function(key). A single element character vector will be passed to this handler, corresponding to the key press. Shift and other modifier keys will have been processed, so shift-a will be passed as "A". The following special keys may also be passed to the handler:

  • Control keys, passed as "Ctrl-A", etc.
  • Navigation keys, passed as one of "Left", "Up", "Right", "Down", "PgUp", "PgDn", "End", "Home"
  • Edit keys, passed as one of "Ins", "Del"
  • Function keys, passed as one of "F1", "F2", ...

The event handlers are standard R functions, and will be executed in an environment as though they had been called directly from getGraphicsEvent.

Events will be processed until

  • one of the event handlers returns a non-NULL value which will be returned as the value of getGraphicsEvent, or
  • the user interrupts the function from the console.

Value

A non-NULL value returned from one of the event handlers.

Author(s)

Duncan Murdoch

Examples

## Not run:
    mousedown <- function(buttons, x, y) {
        cat("Buttons ", paste(buttons, collapse=" "), " at ", x, y, "\n")
        points(x, y)
        if (x > 0.85 && y > 0.85) "Done"
        else NULL
    }

    mousemove <- function(buttons, x, y) {
        points(x, y)
        NULL
    }

    keybd <- function(key) {
        cat("Key <", key, ">\n", sep = "")
    }

    plot(0:1, 0:1, type='n')
    getGraphicsEvent("Click on upper right to quit",
                     onMouseDown = mousedown,
                     onMouseMove = mousemove,
                     onKeybd = keybd)
## End(Not run)


Gray Level Specification

Description

Create a vector of colors from a vector of gray levels.

Usage

gray(level)
grey(level)

Arguments

level a vector of desired gray levels between 0 and 1; zero indicates "black" and one indicates "white".

Details

The values returned by gray can be used with a col= specification in graphics functions or in par.

grey is an alias for gray.

Value

A vector of “colors” of the same length as level.

See Also

rainbow, hsv, hcl, rgb.

Examples

gray(0:8 / 8)


Gray Color Palette

Description

Create a vector of n gamma-corrected gray colors.

Usage

gray.colors(n, start = 0.3, end = 0.9, gamma = 2.2)
grey.colors(n, start = 0.3, end = 0.9, gamma = 2.2)

Arguments

n | the number of gray colors (>= 1) to be in the palette.
start | starting gray level in the palette (should be between 0 and 1 where zero indicates "black" and one indicates "white").
end | ending gray level in the palette.
gamma | the gamma correction.

Details

The function gray.colors chooses a series of n gamma-corrected gray levels between start and end: seq(start^gamma, end^gamma, length = n)^(1/gamma). The returned palette contains the corresponding gray colors. This palette is used in barplot.default.

grey.colors is an alias for gray.colors.

Value

A vector of n gray colors.

See Also

gray, rainbow, palette.

Examples

pie(rep(1,12), col = gray.colors(12))
barplot(1:12, col = gray.colors(12))


Defunct Functions in Package grDevices

Description

The functions or variables listed here are no longer part of R as they are not needed (any more).

Usage

postscriptFont(family, metrics, encoding = "default")

Arguments

family | a character string giving the name of a Type 1 font family.
metrics | a vector of four or five strings giving paths to the afm (font metric) files for the font.
encoding | the name of an encoding file.

Details

The function postscriptFont has been replaced by Type1Font, which is just a change of name.

Value

One or more font mappings.

See Also

Defunct


The R Graphics Devices and Support for Colours and Fonts

Description

Graphics devices and support for base and grid graphics

Details

This package contains functions which support both base and grid graphics.

For a complete list of functions, use library(help="grDevices").

Author(s)

R Development Core Team and contributors worldwide

Maintainer: R Core Team R-core@r-project.org


HCL Color Specification

Description

Create a vector of colors from vectors specifying hue, chroma and luminance.

Usage

hcl(h = 0, c = 35, l = 85, alpha, fixup = TRUE)

Arguments

h | The hue of the color specified as an angle in the range [0,360]. 0 yields red, 120 yields green 240 yields blue, etc.
c | The chroma of the color. The upper bound for chroma depends on hue and luminance.
l | A value in the range [0,100] giving the luminance of the colour. For a given combination of hue and chroma, only a subset of this range is possible.
alpha | numeric value in the range [0,1] for alpha transparency channel (0 means transparent and 1 means opaque).
fixup | a logical value which indicates whether the resulting RGB values should be corrected to ensure that a real color results. if fixup is FALSE RGB components lying outside the range [0,1] will result in an NA value.

Details

This function corresponds to polar coordinates in the CIE-LUV color space. Steps of equal size in this space correspond to approximately equal peceptual changes in color. Thus, hcl can be thought of as a perceptually based version of hsv.

The function is primarily intended as a way of computing colors for filling areas in plots where area corresponds to a numerical value (pie charts, bar charts, mosaic plots, histograms, etc). Choosing colors which have equal chroma and luminance provides a way of minimising the irradiation illusion which would otherwise produce a misleading impression of how large the areas are.

The default values of chroma and luminance make it possible to generate a full range of hues and have a relatively pleasant pastel appearance.

The RGB values produced by this function correspond to the sRGB color space used on most PC computer displays. There are other packages which provide more general color space facilities.

Value

A vector of character strings which can be used as color specifications by R graphics functions.

Note

At present there is no guarantee that the colours rendered by R graphics devices will correspond to their sRGB description. It is planned to adopt sRGB as the standard R color description in future.

Author(s)

Ross Ihaka

References

Ihaka, R. (2003). Colour for Presentation Graphics, Proceedings of the 3rd International Workshop on Distributed Statistical Computing (DSC 2003), March 20-22, 2003, Technische Universität Wien, Vienna, Austria. http://www.ci.tuwien.ac.at/Conferences/DSC-2003.

See Also

hsv, rgb.

Examples

# The Foley and Van Dam PhD Data.
csd <- matrix(c( 4,2,4,6, 4,3,1,4, 4,7,7,1,
                 0,7,3,2, 4,5,3,2, 5,4,2,2,
                 3,1,3,0, 4,4,6,7, 1,10,8,7,
                 1,5,3,2, 1,5,2,1, 4,1,4,3,
                 0,3,0,6, 2,1,5,5), nr=4)

csphd =
function(colors)
barplot(csd, col = colors, ylim = c(0,30),
        names = 72:85, xlab = "Year", ylab = "Students",
        legend = c("Winter", "Spring", "Summer", "Fall"),
        main = "Computer Science PhD Graduates", las = 1)

# The Original (Metaphorical) Colors (Ouch!)
csphd(c("blue", "green", "yellow", "orange"))

# A Color Tetrad (Maximal Color Differences)
csphd(hcl(h = c(30, 120, 210, 300)))

# Same, but lighter and less colorful
# Turn of automatic correction to make sure
# that we have defined real colors.
csphd(hcl(h = c(30, 120, 210, 300),
          c = 20, l = 90, fixup = FALSE))

# Analogous Colors
# Good for those with red/green color confusion
csphd(hcl(h = seq(60, 240, by = 60)))

# Metaphorical Colors
csphd(hcl(h = seq(210, 60, length = 4)))

# Cool Colors
csphd(hcl(h = seq(120, 0, length = 4) + 150))

# Warm Colors
csphd(hcl(h = seq(120, 0, length = 4) - 30))

# Single Color
hist(rnorm(1000), col = hcl(240))


Hershey Vector Fonts in R

Description

If the family graphical parameter (see par) has been set to one of the Hershey fonts (see below) Hershey vector fonts are used to render text.

These fonts have two advantages:

  1. vector fonts describe each character in terms of a set of points; R renders the character by joining up the points with straight lines. This intimate knowledge of the outline of each character means that R can arbitrarily transform the characters, which can mean that the vector fonts look better for rotated and 3d text. This works for Latin-1 and Cyrillic characters, only.
  2. this implementation was adapted from the GNU libplot library which provides support for non-ASCII and non-English fonts. This means that it is possible, for example, to produce weird plotting symbols and Japanese characters.

For historical reasons, when using the text function, Hershey fonts may also be selected via the vfont argument, which is a character vector of length 2 (see below for valid values).

Drawback:
You cannot use mathematical expressions (plotmath) with Hershey fonts.

Usage

Hershey

Details

The Hershey characters are organised into a set of fonts. A particular font is selected by specifying one of the following font families via par(family) and specifying the desired font face (plain, bold, italic, bold-italic) via par(font).

family | faces available
"HersheySerif" | plain, bold, italic, bold-italic
"HersheySans" | plain, bold, italic, bold-italic
"HersheyScript" | plain, bold
"HersheyGothicEnglish" | plain
"HersheyGothicGerman" | plain
"HersheyGothicItalian" | plain
"HersheySymbol" | plain, bold, italic, bold-italic
"HersheySansSymbol" | plain, italic

In the old, vfont specification for the text function, the Hershey font is specified by a typeface (e.g., serif or sans serif) and a fontindex or “style” (e.g., plain or italic). The first element of vfont specifies the typeface and the second element specifies the fontindex. The first table produced by demo(Hershey) shows the character a produced by each of the different fonts.

The available typeface and fontindex values are available as list components of the variable Hershey. The allowed pairs for (typeface, fontindex) are:

serif | plain
serif | italic
serif | bold
serif | bold italic
serif | cyrillic
serif | oblique cyrillic
serif | EUC
sans serif | plain
sans serif | italic
sans serif | bold
sans serif | bold italic
script | plain
script | italic
script | bold
gothic english | plain
gothic german | plain
gothic italian | plain
serif symbol | plain
serif symbol | italic
serif symbol | bold
serif symbol | bold italic
sans serif symbol | plain
sans serif symbol | italic

and the indices of these are available as Hershey$allowed.

Escape sequences:
The string to be drawn can include escape sequences, which all begin with a \. When R encounters a \, rather than drawing the \, it treats the subsequent character(s) as a coded description of what to draw.

One useful escape sequence (in the current context) is of the form: \123. The three digits following the \ specify an octal code for a character. For example, the octal code for p is 160 so the strings "p" and "\160" are equivalent. This is useful for producing characters when there is not an appropriate key on your keyboard.

The other useful escape sequences all begin with \\. These are described below. Remember that backslashes have to be doubled in R character strings, so they need to be entered with four backslashes.

Symbols:
an entire string of Greek symbols can be produced by selecting the Serif Symbol or Sans Serif Symbol typeface. To allow Greek symbols to be embedded in a string which uses a non-symbol typeface, there are a set of symbol escape sequences of the form \\ab. For example, the escape sequence \\*a produces a Greek alpha. The second table in demo(Hershey) shows all of the symbol escape sequences and the symbols that they produce.
ISO Latin-1:
further escape sequences of the form \\ab are provided for producing ISO Latin-1 characters. Another option is to use the appropriate octal code. The (non-ASCII) ISO Latin-1 characters are in the range 241...377. For example, \366 produces the character o with an umlaut. The third table in demo(Hershey) shows all of the ISO Latin-1 escape sequences.

These characters can be used directly in a Latin-1 or UTF-8 locale. (In the latter, non-Latin-1 characters are replaced by a dot.)

Special Characters:
a set of characters are provided which do not fall into any standard font. These can only be accessed by escape sequence. For example, \\LI produces the zodiac sign for Libra, and \\JU produces the astronomical sign for Jupiter. The fourth table in demo(Hershey) shows all of the special character escape sequences.
Cyrillic Characters:
cyrillic characters are implemented according to the K018-R encoding, and can be used directly in such a locale using the Serif typeface and Cyrillic (or Oblique Cyrillic) fontindex. Alternatively they can be specified via an octal code in the range 300 to 337 for lower case characters or 340 to 377 for upper case characters. The fifth table in demo(Hershey) shows the octal codes for the available cyrillic characters.

Cyrillic has to be selected via a ("serif", fontindex) pair rather than via a font family.

Japanese Characters:
83 Hiragana, 86 Katakana, and 603 Kanji characters are implemented according to the EUC-JP (Extended Unix Code) encoding. Each character is identified by a unique hexadecimal code. The Hiragana characters are in the range 0x2421 to 0x2473, Katakana are in the range 0x2521 to 0x2576, and Kanji are (scattered about) in the range 0x3021 to 0x6d55.

When using the Serif typeface and EUC fontindex, these characters can be produced by a pair of octal codes. Given the hexadecimal code (e.g., 0x2421), take the first two digits and add 0x80 and do the same to the second two digits (e.g., 0x21 and 0x24 become 0xa4 and 0xa1), then convert both to octal (e.g., 0xa4 and 0xa1 become 244 and 241). For example, the first Hiragana character is produced by \244\241.

It is also possible to use the hexadecimal code directly. This works for all non-EUC fonts by specifying an escape sequence of the form \\#J1234. For example, the first Hiragana character is produced by \\#J2421.

The Kanji characters may be specified in a third way, using the so-called "Nelson Index", by specifying an escape sequence of the form \\#N1234. For example, the Kanji for “one” is produced by \\#N0001.

demo(Japanese) shows the available Japanese characters.

Raw Hershey Glyphs:
all of the characters in the Hershey fonts are stored in a large array. Some characters are not accessible in any of the Hershey fonts. These characters can only be accessed via an escape sequence of the form \\#H1234. For example, the fleur-de-lys is produced by \\#H0746. The sixth and seventh tables of demo(Hershey) shows all of the available raw glyphs.

References

http://www.gnu.org/software/plotutils/plotutils.html

See Also

demo(Hershey), par, text, contour.

Japanese for the Japanese characters in the Hershey fonts.

Examples

Hershey

## for tables of examples, see demo(Hershey)


HSV Color Specification

Description

Create a vector of colors from vectors specifying hue, saturation and value.

Usage

hsv(h = 1, s = 1, v = 1, gamma = 1, alpha)

Arguments

h,s,v | numeric vectors of values in the range [0,1] for “hue”, “saturation” and “value” to be combined to form a vector of colors. Values in shorter arguments are recycled.
gamma | a “gamma correction” exponent, gamma
alpha | numeric value in the range [0,1] for alpha transparency channel (0 means transparent and 1 means opaque).

Value

This function creates a vector of “colors” corresponding to the given values in HSV space. The values returned by hsv can be used with a col= specification in graphics functions or in par.

Gamma correction

For each color, (r,g,b) in RGB space (with all values in [0,1]), the final color corresponds to (r^{gamma}, g^{gamma}, b^{gamma}).

See Also

hcl for a perceptually based version of hsv(), rgb and rgb2hsv for RGB to HSV conversion; rainbow, gray.

Examples

hsv(.5,.5,.5)

## Look at gamma effect:
n <- 20;  y <- -sin(3*pi*((1:n)-1/2)/n)
op <- par(mfrow=c(3,2),mar=rep(1.5,4))
for(gamma in c(.4, .6, .8, 1, 1.2, 1.5))
  plot(y, axes = FALSE, frame.plot = TRUE,
       xlab = "", ylab = "", pch = 21, cex = 30,
       bg = rainbow(n, start=.85, end=.1, gamma = gamma),
       main = paste("Red tones;  gamma=",format(gamma)))
par(op)


Japanese characters in R

Description

The implementation of Hershey vector fonts provides a large number of Japanese characters (Hiragana, Katakana, and Kanji).

Details

Without keyboard support for typing Japanese characters, the only way to produce these characters is to use special escape sequences: see Hershey.

For example, the Hiragana character for the sound "ka" is produced by \\#J242b and the Katakana character for this sound is produced by \\#J252b. The Kanji ideograph for "one" is produced by \\#J306c or \\#N0001.

The output from demo(Japanese) shows tables of the escape sequences for the available Japanese characters.

References

http://www.gnu.org/software/plotutils/plotutils.html

See Also

demo(Japanese), Hershey, text, contour

Examples

plot(1:9, type="n", axes=FALSE, frame=TRUE, ylab="",
     main= "example(Japanese)", xlab= "using Hershey fonts")
par(cex=3)
Vf <- c("serif", "plain")
text(4, 2, "\\#J2438\\#J2421\\#J2451\\#J2473", vfont = Vf)
text(4, 4, "\\#J2538\\#J2521\\#J2551\\#J2573", vfont = Vf)
text(4, 6, "\\#J467c\\#J4b5c", vfont = Vf)
text(4, 8, "Japan", vfont = Vf)
par(cex=1)
text(8, 2, "Hiragana")
text(8, 4, "Katakana")
text(8, 6, "Kanji")
text(8, 8, "English")


Create colour spaces

Description

These functions specify colour spaces for use in convertColor.

Usage

make.rgb(red, green, blue, name = NULL, white = "D65", gamma = 2.2)
colorConverter(toXYZ, fromXYZ, name, white=NULL)

Arguments

red,green,blue | Chromaticity (xy or xyY) of RGB primaries
name | Name for the colour space
white | Character string specifying the reference white (see Details)
gamma | Display gamma (nonlinearity). A positive number or the string "sRGB"
fromXYZ | Function to convert from XYZ tristimulus coordinates to this space
toXYZ | Function to convert from this space to XYZ tristimulus coordinates.

Details

An RGB colour space is defined by the chromaticities of the red, green and blue primaries. These are given as vectors of length 2 or 3 in xyY coordinates (the Y component is not used and may be omitted). The chromaticities are defined relative to a reference white, which must be one of the CIE standard illuminants: "A", "B", "C", "D50", "D55", "D60", "E" (usually "D65").

The display gamma is most commonly 2.2, though 1.8 is used for Apple RGB. The sRGB standard specifies a more complicated function that is close to a gamma of 2.2; gamma="sRGB" uses this function.

Colour spaces other than RGB can be specified directly by giving conversions to and from XYZ tristimulus coordinates. The functions should take two arguments. The first is a vector giving the coordinates for one colour. The second argument is the reference white. If a specific reference white is included in the definition of the colour space (as for the RGB spaces) this second argument should be ignored and may be ....

Value

An object of class colorConverter

References

Conversion algorithms from http://www.brucelindbloom.com

See Also

convertColor

Examples

(pal <- make.rgb(red=  c(0.6400,0.3300),
                 green=c(0.2900,0.6000),
                 blue= c(0.1500,0.0600),
                 name = "PAL/SECAM RGB"))

## converter for sRGB in #rrggbb format
hexcolor <- colorConverter(toXYZ = function(hex,...) {
                            rgb <- t(col2rgb(hex))/255
                            colorspaces$sRGB$toXYZ(rgb,...) },
                           fromXYZ = function(xyz,...) {
                              rgb <- colorspaces$sRGB$fromXYZ(xyz,..)
                              rgb <- round(rgb,5)
                              if (min(rgb) < 0 || max(rgb) > 1)
                                   as.character(NA)
                              else
                                   rgb(rgb[1],rgb[2],rgb[3])},
                           white = "D65", name = "#rrggbb")

(cols <- t(col2rgb(palette())))
(luv <- convertColor(cols,from="sRGB", to="Luv", scale.in=255))
(hex <- convertColor(luv, from="Luv",  to=hexcolor, scale.out=NULL))

## must make hex a matrix before using it
(cc <- round(convertColor(as.matrix(hex), from= hexcolor, to= "sRGB",
                          scale.in=NULL, scale.out=255)))
stopifnot(cc == cols)


Compute Default mfrow From Number of Plots

Description

Easy setup for plotting multiple figures (in a rectangular layout) on one page. This computes a sensible default for par(mfrow).

Usage

n2mfrow(nr.plots)

Arguments

nr.plots integer; the number of plot figures you'll want to draw.

Value

A length two integer vector nr, nc giving the number of rows and columns, fulfilling nr >= nc >= 1 and nr * nc >= nr.plots.

Author(s)

Martin Maechler

See Also

par, layout.

Examples

n2mfrow(8) # 3 x 3

n <- 5 ; x <- seq(-2,2, len=51)
## suppose now that 'n' is not known {inside function}
op <- par(mfrow = n2mfrow(n))
for (j in 1:n)
   plot(x, x^j, main = substitute(x^ exp, list(exp = j)), type = "l",
   col = "blue")

sapply(1:10, n2mfrow)


Compute the Number of Classes for a Histogram

Description

Compute the number of classes for a histogram.

Usage

nclass.Sturges(x)
nclass.scott(x)
nclass.FD(x)

Arguments

x A data vector.

Details

nclass.Sturges uses Sturges' formula, implicitly basing bin sizes on the range of the data.

nclass.scott uses Scott's choice for a normal distribution based on the estimate of the standard error.

nclass.FD uses the Freedman-Diaconis choice based on the inter-quartile range.

Value

The suggested number of classes.

References

Venables, W. N. and Ripley, B. D. (2002) Modern Applied Statistics with S-PLUS. Springer, page 112.

Freedman, D. and Diaconis, P. (1981) On the histogram as a density estimator: L_2 theory. Zeitschrift für Wahrscheinlichkeitstheorie und verwandte Gebiete 57, 453–476.

Scott, D. W. (1979) On optimal and data-based histograms. Biometrika 66, 605–610.

Scott, D. W. (1992) Multivariate Density Estimation. Theory, Practice, and Visualization. Wiley.

See Also

hist


Set or View the Graphics Palette

Description

View or manipulate the color palette which is used when a col= has a numeric index.

Usage

palette(value)

Arguments

value an optional character vector.

Details

If value has length 1, it is taken to be the name of a built in color palette. If value has length greater than 1 it is assumed to contain a description of the colors which are to make up the new palette (either by name or by RGB levels).

If value is omitted or has length 0, no change is made the current palette.

Currently, the only built-in palette is "default".

Value

The palette which was in effect. This is invisible unless the argument is omitted.

See Also

colors for the vector of built-in “named” colors; hsv, gray, rainbow, terrain.colors,... to construct colors.

colorRamp to interpolate colors, making custom palettes; col2rgb for translating colors to RGB 3-vectors.

Examples

palette()               # obtain the current palette
palette(rainbow(6))     # six color rainbow

(palette(gray(seq(0,.9,len=25)))) # gray scales; print old palette
matplot(outer(1:100,1:30), type='l', lty=1,lwd=2, col=1:30,
        main = "Gray Scales Palette",
        sub = "palette(gray(seq(0,.9,len=25)))")
palette("default")      # reset back to the default


Color Palettes

Description

Create a vector of n “contiguous” colors.

Usage

rainbow(n, s = 1, v = 1, start = 0, end = max(1,n - 1)/n,
        gamma = 1, alpha = 1)
heat.colors(n, alpha = 1)
terrain.colors(n, alpha = 1)
topo.colors(n, alpha = 1)
cm.colors(n, alpha = 1)

Arguments

n | the number of colors (>= 1) to be in the palette.
s,v | the “saturation” and “value” to be used to complete the HSV color descriptions.
start | the (corrected) hue in [0,1] at which the rainbow begins.
end | the (corrected) hue in [0,1] at which the rainbow ends.
gamma | the gamma correction, see argument gamma in hsv.
alpha | the alpha transparency, a number in [0,1], see argument alpha in hsv.

Details

Conceptually, all of these functions actually use (parts of) a line cut out of the 3-dimensional color space, parametrized by hsv(h,s,v, gamma), where gamma=1 for the foo.colors function, and hence, equispaced hues in RGB space tend to cluster at the red, green and blue primaries.

Some applications such as contouring require a palette of colors which do not “wrap around” to give a final color close to the starting one.

With rainbow, the parameters start and end can be used to specify particular subranges of hues. The following values can be used when generating such a subrange: red=0, yellow=1/6, green=2/6, cyan=3/6, blue=4/6 and magenta=5/6.

Value

A character vector, cv, of color names. This can be used either to create a user–defined color palette for subsequent graphics by palette(cv), a col= specification in graphics functions or in par.

See Also

colors, palette, hsv, hcl, rgb, gray and col2rgb for translating to RGB numbers.

Examples

require(graphics)
# A Color Wheel
pie(rep(1,12), col=rainbow(12))

##------ Some palettes ------------
demo.pal <-
  function(n, border = if (n<32) "light gray" else NA,
           main = paste("color palettes;  n=",n),
           ch.col = c("rainbow(n, start=.7, end=.1)", "heat.colors(n)",
                      "terrain.colors(n)", "topo.colors(n)",
                      "cm.colors(n)"))
{
    nt <- length(ch.col)
    i <- 1:n; j <- n / nt; d <- j/6; dy <- 2*d
    plot(i,i+d, type="n", yaxt="n", ylab="", main=main)
    for (k in 1:nt) {
        rect(i-.5, (k-1)*j+ dy, i+.4, k*j,
             col = eval(parse(text=ch.col[k])), border = border)
        text(2*j,  k * j +dy/4, ch.col[k])
    }
}
n <- if(.Device == "postscript") 64 else 16
     # Since for screen, larger n may give color allocation problem
demo.pal(n)


PDF Graphics Device

Description

pdf starts the graphics device driver for producing PDF graphics.

Usage

pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot%03d.pdf"),
    width = 6, height = 6, onefile = TRUE, family = "Helvetica",
    title = "R Graphics Output", fonts = NULL, version = "1.1",
    paper = "special", encoding, bg, fg, pointsize, pagecentre)

Arguments

file | a character string giving the name of the file. For use with onefile=FALSE give a C integer format such as "Rplot%03d.pdf" (the default in that case). (See postscript for further details.)
width, height | the width and height of the graphics region in inches.
onefile | logical: if true (the default) allow multiple figures in one file. If false, generate a file name containing the page number.
family | the font family to be used, see postscript.
title | title string to embed in the file.
fonts | a character vector specifying R graphics font family names for fonts which will be included in the PDF file.
version | a string describing the PDF version that will be required to view the output. This is a minimum, and will be increased (with a warning) if necessary.
paper | the size of paper in the printer. The choices are "a4", "letter", "legal" and "executive" (and these can be capitalized). The default is "special", which means that the width and height specify the paper size. A further choice is "default"; if this is selected, the papersize is taken from the option "papersize" if that is set and to "a4" if it is unset or empty.
encoding | the name of an encoding file. See postscript for details.
bg | the default background color to be used.
fg | the default foreground color to be used.
pointsize | the default point size to be used. Strictly speaking, in bp, that is 1/72 of an inch, but approximately in points.
pagecentre | logical: should the device region be centred on the page? – defaults to true, but is only relevant for paper != "special".

Details

pdf() opens the file file and the PDF commands needed to plot any graphics requested are sent to that file.

The file argument is interpreted as a C integer format as used by sprintf, with integer argument the page number. The default gives files ‘Rplot001.pdf’, ..., ‘Rplot999.pdf’, ‘Rplot1000.pdf’, ....

The family argument can be used to specify a PDF-specific font family as the initial/default font for the device.

If a device-independent R graphics font family is specified (e.g., via par(family=) in the graphics package), the PDF device makes use of the PostScript font mappings to convert the R graphics font family to a PDF-specific font family description. (See the documentation for pdfFonts.)

R does not embed fonts in the PDF file though, so it is only possible straightforward to use mappings to the font families that are assumed to be available in any PDF viewer: "Times" (equivalently "serif"), "Helvetica" (equivalently "sans"), "Courier" (equivalently "mono") and "Symbol" (equivalently "symbol"). Other families may be specified, but it is the user's responsibility to ensure that these fonts are available on the system and third-party software, e.g., ghostscript, may be required to embed the fonts so that the PDF can be included in other documents (e.g., LaTeX). The URW-based families described for postscript can be used with viewers such as GSView which are based on URW fonts.

See postscript for details of encodings, as the internal code is shared between the drivers. The native PDF encoding is given in file ‘PDFDoc.enc’.

pdf writes uncompressed PDF. It is primarily intended for producing PDF graphics for inclusion in other documents, and PDF-includers such as pdftex are usually able to handle compression.

At present the PDF is fairly simple, with each page being represented as a single stream. The R graphics model does not distinguish graphics objects at the level of the driver interface.

The version argument declares the version of PDF that gets produced. The version must be at least 1.4 for semitransparent output to be understood, and at least 1.3 if CID fonts are to be used: if these features are used the version number will be increased (with a warning). Specifying a low version number (as the default) is useful if you want to produce PDF output that can be viewed on older or non-Adobe PDF viewers. (PDF 1.4 requires Acrobat 5 or later.)

Line widths as controlled by par(lwd=) are in multiples of 1/96 inch. Multiples less than 1 are allowed. pch="." with cex = 1 corresponds to a square of side 1/72 inch.

Note

Acrobat Reader does not use the fonts specified but rather emulates them from multiple-master fonts. This can be seen in imprecise centering of characters, for example the multiply and divide signs in Helvetica.

Acrobat Reader 5.x and later can be extended by support for Asian and (so-called) Central European fonts (the latter only for 7.x), and this will be needed for full use of encodings other than Latin-1. See http://www.adobe.com/products/acrobat/acrrasianfontpack.html.

See Also

pdfFonts, Devices, postscript

Examples

## Not run:
## Test function for encodings
TestChars <- function(encoding="ISOLatin1", ...)
{
    pdf(encoding=encoding, ...)
    par(pty="s")
    plot(c(-1,16), c(-1,16), type="n", xlab="", ylab="", xaxs="i", yaxs="i")
    title(paste("Centred chars in encoding", encoding))
    grid(17, 17, lty=1)
    for(i in c(32:255)) {
        x <- i %% 16
        y <- i %/% 16
        points(x, y, pch=i)
    }
    dev.off()
}
## there will be many warnings.
TestChars("ISOLatin2")
## this does not view properly in older viewers.
TestChars("ISOLatin2", family="URWHelvetica")
## works well for viewing in gs-based viewers, and often in xpdf.
## End(Not run)


A PicTeX Graphics Driver

Description

This function produces graphics suitable for inclusion in TeX and LaTeX documents.

Usage

pictex(file = "Rplots.tex", width = 5, height = 4, debug = FALSE,
       bg = "white", fg = "black")

Arguments

file | the file where output will appear.
width | The width of the plot in inches.
height | the height of the plot in inches.
debug | should debugging information be printed.
bg | the background color for the plot. Ignored.
fg | the foreground color for the plot. Ignored.

Details

This driver does not have any font metric information, so the use of plotmath is not supported.

Multiple plots will be placed as separate environments in the output file.

Line widths are ignored except when setting the spacing of line textures. pch="." corresponds to a square of side 1pt.

This device does not support colour (nor does the PicTeX package), and all colour settings are ignored.

Author(s)

This driver was provided by Valerio Aimale valerio@svpop.com.dist.unige.it of the Department of Internal Medicine, University of Genoa, Italy.

References

Knuth, D. E. (1984) The TeXbook. Reading, MA: Addison-Wesley.

Lamport, L. (1994) LATEX: A Document Preparation System. Reading, MA: Addison-Wesley.

Goossens, M., Mittelbach, F. and Samarin, A. (1994) The LATEX Companion. Reading, MA: Addison-Wesley.

See Also

postscript, Devices.

Examples

pictex()
plot(1:11,(-5:5)^2, type='b', main="Simple Example Plot")
dev.off()
##--------------------
## Not run:
%% LaTeX Example
\documentclass{article}
\usepackage{pictex}
\begin{document}
%...
\begin{figure}[h]
  \centerline{\input{Rplots.tex}}
  \caption{}
\end{figure}
%...
\end{document}

%%-- plain TeX Example --
\input pictex
$$ \input Rplots.tex $$
## End(Not run)
##--------------------
unlink("Rplots.tex")


Mathematical Annotation in R

Description

If the text argument to one of the text-drawing functions (text, mtext, axis, legend) in R is an expression, the argument is interpreted as a mathematical expression and the output will be formatted according to TeX-like rules. Expressions can also be used for titles, subtitles and x- and y-axis labels (but not for axis labels on persp plots).

In most cases other language objects (names and calls) are coerced to expressions and so can also be used.

Details

A mathematical expression must obey the normal rules of syntax for any R expression, but it is interpreted according to very different rules than for normal R expressions.

It is possible to produce many different mathematical symbols, generate sub- or superscripts, produce fractions, etc.

The output from demo(plotmath) includes several tables which show the available features. In these tables, the columns of grey text show sample R expressions, and the columns of black text show the resulting output.

The available features are also described in the tables below:

Syntax | Meaning
x + y | x plus y
x - y | x minus y
x*y | juxtapose x and y
x/y | x forwardslash y
x %+-% y | x plus or minus y
x %/% y | x divided by y
x %*% y | x times y
x %.% y | x cdot y
x[i] | x subscript i
x^2 | x superscript 2
paste(x, y, z) | juxtapose x, y, and z
sqrt(x) | square root of x
sqrt(x, y) | yth root of x
x == y | x equals y
x != y | x is not equal to y
x < y | x is less than y
x <= y | x is less than or equal to y
x > y | x is greater than y
x >= y | x is greater than or equal to y
x %~~% y | x is approximately equal to y
x %=~% y | x and y are congruent
x %==% y | x is defined as y
x %prop% y | x is proportional to y
plain(x) | draw x in normal font
bold(x) | draw x in bold font
italic(x) | draw x in italic font
bolditalic(x) | draw x in bolditalic font
list(x, y, z) | comma-separated list
... | ellipsis (height varies)
cdots | ellipsis (vertically centred)
ldots | ellipsis (at baseline)
x %subset% y | x is a proper subset of y
x %subseteq% y | x is a subset of y
x %notsubset% y | x is not a subset of y
x %supset% y | x is a proper superset of y
x %supseteq% y | x is a superset of y
x %in% y | x is an element of y
x %notin% y | x is not an element of y
hat(x) | x with a circumflex
tilde(x) | x with a tilde
dot(x) | x with a dot
ring(x) | x with a ring
bar(xy) | xy with bar
widehat(xy) | xy with a wide circumflex
widetilde(xy) | xy with a wide tilde
x %<->% y | x double-arrow y
x %->% y | x right-arrow y
x %<-% y | x left-arrow y
x %up% y | x up-arrow y
x %down% y | x down-arrow y
x %<=>% y | x is equivalent to y
x %=>% y | x implies y
x %<=% y | y implies x
x %dblup% y | x double-up-arrow y
x %dbldown% y | x double-down-arrow y
alpha – omega | Greek symbols
Alpha – Omega | uppercase Greek symbols
theta1, phi1, sigma1, omega1 | cursive Greek symbols
Upsilon1 | capital upsilon with hook
infinity | infinity symbol
partialdiff | partial differential symbol
32*degree | 32 degrees
60*minute | 60 minutes of angle
30*second | 30 seconds of angle
displaystyle(x) | draw x in normal size (extra spacing)
textstyle(x) | draw x in normal size
scriptstyle(x) | draw x in small size
scriptscriptstyle(x) | draw x in very small size
underline(x) | draw x underlined
x ~~ y | put extra space between x and y
x + phantom(0) + y | leave gap for "0", but don't draw it
x + over(1, phantom(0)) | leave vertical gap for "0" (don't draw)
frac(x, y) | x over y
over(x, y) | x over y
atop(x, y) | x over y (no horizontal bar)
sum(x[i], i==1, n) | sum x[i] for i equals 1 to n
prod(plain(P)(X==x), x) | product of P(X=x) for all values of x
integral(f(x)*dx, a, b) | definite integral of f(x) wrt x
union(A[i], i==1, n) | union of A[i] for i equals 1 to n
intersect(A[i], i==1, n) | intersection of A[i]
lim(f(x), x %->% 0) | limit of f(x) as x tends to 0
min(g(x), x > 0) | minimum of g(x) for x greater than 0
inf(S) | infimum of S
sup(S) | supremum of S
x^y + z | normal operator precedence
x^(y + z) | visible grouping of operands
x^{y + z} | invisible grouping of operands
group("(",list(a, b),"]") | specify left and right delimiters
bgroup("(",atop(x,y),")") | use scalable delimiters
group(lceil, x, rceil) | special delimiters

Note to TeX users: TeX's \Upsilon is Upsilon1, TeX's \varepsilon is close to epsilon, and there is no equivalent of TeX's \epsilon. TeX's \varpi is close to omega1. vartheta, varphi and varsigma are allowed as synonyms for theta1, phi1 and sigma1.

sigma1 is also known as stigma, its Unicode name.

Control characters (e.g. \n) are not interpreted in character strings in plotmath, unlike normal plotting.

References

Murrell, P. and Ihaka, R. (2000) An approach to providing mathematical annotation in plots. Journal of Computational and Graphical Statistics, 9, 582–599.

See Also

demo(plotmath), axis, mtext, text, title, substitute quote, bquote

Examples

x <- seq(-4, 4, len = 101)
y <- cbind(sin(x), cos(x))
matplot(x, y, type = "l", xaxt = "n",
        main = expression(paste(plain(sin) * phi, "  and  ",
                                plain(cos) * phi)),
        ylab = expression("sin" * phi, "cos" * phi), # only 1st is taken
        xlab = expression(paste("Phase Angle ", phi)),
        col.main = "blue")
axis(1, at = c(-pi, -pi/2, 0, pi/2, pi),
     labels = expression(-pi, -pi/2, 0, pi/2, pi))

## How to combine "math" and numeric variables :
plot(1:10, type="n", xlab="", ylab="", main = "plot math & numbers")
theta <- 1.23 ; mtext(bquote(hat(theta) == .(theta)))
for(i in 2:9)
    text(i,i+1, substitute(list(xi,eta) == group("(",list(x,y),")"),
                           list(x=i, y=i+1)))
## note that both of these use calls rather than expressions.

plot(1:10, 1:10)
text(4, 9, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(4, 8.4, "expression(hat(beta) == (X^t * X)^{-1} * X^t * y)",
     cex = .8)
text(4, 7, expression(bar(x) == sum(frac(x[i], n), i==1, n)))
text(4, 6.4, "expression(bar(x) == sum(frac(x[i], n), i==1, n))",
     cex = .8)
text(8, 5, expression(paste(frac(1, sigma*sqrt(2*pi)), " ",
                            plain(e)^{frac(-(x-mu)^2, 2*sigma^2)})),
     cex = 1.2)


BMP, JPEG and PNG graphics devices

png(grDevices) R Documentation

BMP JPEG and PNG graphics devices

Description

A graphics device for BMP, JPEG or PNG format bitmap files.

Usage

bmp(filename = "Rplot%03d.bmp", width = 480, height = 480,
    pointsize = 12, bg = "white", res = NA, restoreConsole = TRUE)
jpeg(filename = "Rplot%03d.jpg", width = 480, height = 480,
     pointsize = 12, quality = 75, bg = "white", res = NA,
     restoreConsole = TRUE)
png(filename = "Rplot%03d.png", width = 480, height = 480,
    pointsize = 12, bg = "white", res = NA, restoreConsole = TRUE)

Arguments

filename | the name of the output file, up to 511 characters. The page number is substituted if a C integer format is included in the character string, as in the default. (The result must be less than 600 characters long. See postscript for further details.)
width | the width of the device in pixels.
height | the height of the device in pixels.
pointsize | the default pointsize of plotted text, interpreted at 72 dpi, so one point is approximately one pixel.
bg | the initial background colour: can be overridden by setting par("bg").
quality | the ‘quality’ of the JPEG image, as a percentage. Smaller values will give more compression but also more degradation of the image.
res | The nominal resolution in dpi which will be recorded in the bitmap file, if a positive integer.
restoreConsole | See the Details section of windows

Details

Plots in PNG and JPEG format can easily be converted to many other bitmap formats, and both can be displayed in most modern web browsers. The PNG format is lossless and is best for line diagrams and blocks of solid colour. The JPEG format is lossy, but may be useful for image plots, for example. The BMP format is standard on Windows, and supported elsewhere.

png supports transparent backgrounds on 16-bit (‘High Color’) or better screens: use bg = "transparent". Not all PNG viewers render files with transparency correctly.

Windows imposes limits on the size of bitmaps: these are not documented in the SDK and may depend on the version of Windows. It seems that width and height are each limited to 2^15-1 and there is a 16Mb limit on the total amount of memory in Windows 95/98/ME.

By default no resolution is recorded in the file. Readers will often assume nominal resolution of 72dpi when none is recorded. As resolutions in PNG files are recorded in pixels/metre, the dpi value will be changed slightly.

Both bmp and png will use a palette if there are less than 256 colours on the page, and record a 24-bit RGB file otherwise.

Value

A plot device is opened: nothing is returned to the R interpreter.

Warnings

Note that the width and height are in pixels not inches. A warning will be issued if both are less than 20.

If you plot more than one page on one of these devices and do not include something like %d for the sequence number in file, the file will contain the last page plotted.

Note

These devices effectively plot on a hidden screen and then copy the image to the required format. This means that they have the same colour handling as the actual screen device, and work best if that is set to a 24-bit or 32-bit colour mode.

See Also

Devices, dev.print, bitmap

Examples

## copy current plot to a (large) PNG file
## Not run: dev.print(png, file="myplot.png", width=1024, height=768)

png(file="myplot.png", bg="transparent")
plot(1:10)
rect(1, 5, 3, 7, col="white")
dev.off()

jpeg(file="myplot.jpeg")
example(rect)
dev.off()
## End(Not run)


PostScript Graphics

Description

postscript starts the graphics device driver for producing PostScript graphics.

Usage

postscript(file = ifelse(onefile, "Rplots.ps", "Rplot%03d.ps"),
           onefile = TRUE, family,
           title = "R Graphics Output", fonts = NULL,
           encoding, bg, fg,
           width, height, horizontal, pointsize,
           paper, pagecentre, print.it, command)

Arguments

file | a character string giving the name of the file. If it is "", the output is piped to the command given by the argument command. For use with onefile = FALSE give a printf format such as "Rplot%03d.ps" (the default in that case).
onefile | logical: if true (the default) allow multiple figures in one file. If false, generate a file name containing the page number and use an EPSF header and no DocumentMedia comment.
family | the initial font family to be used, normally as a character string. See the section ‘Families’. This defaults to "Helvetica".
title | title string to embed in the file.
fonts | a character vector specifying additional R graphics font family names for font families whose declarations will be included in the PostScript file and are available for use with the device. See Details.
encoding | the name of an encoding file. Defaults to ‘"CP1250.enc"’ (East European), "CP1251.enc" (Cyrillic), "CP1253.enc" (Greek) or "CP1257.enc" (Baltic) if one of those codepages is in use, otherwise ‘"WinAnsi.enc"’ (codepage 1252), in the ‘enc’ directory of package grDevices, which is used if the path does not contain a path separator. An extension ".enc" can be omitted.
bg | the default background color to be used. If "transparent" (or an equivalent specification), no background is painted.
fg | the default foreground color to be used.
width, height | the width and height of the graphics region in inches. The default is to use the entire page less a 0.25 inch border on each side.
horizontal | the orientation of the printed image, a logical. Defaults to true, that is landscape orientation on paper sizes with width less than height.
pointsize | the default point size to be used. Strictly speaking, in bp, that is 1/72 of an inch, but approximately in points.
paper | the size of paper in the printer. The choices are "a4", "letter", "legal" and "executive" (and these can be capitalized). Also, "special" can be used, when the width and height specify the paper size. A further choice is "default", which is the default. If this is selected, the papersize is taken from the option "papersize" if that is set and to "a4" if it is unset or empty.
pagecentre | logical: should the device region be centred on the page? – defaults to true.
print.it | logical: should the file be printed when the device is closed? (This only applies if file is a real file name.)
command | the command to be used for “printing”. Defaults to option "printcmd"; this can also be selected as "default".

Details

postscript opens the file file and the PostScript commands needed to plot any graphics requested are written to that file. This file can then be printed on a suitable device to obtain hard copy.

A postscript plot can be printed via postscript in two ways.

  1. Setting print.it = TRUE causes the command given in argument command to be called with argument "file" when the device is closed. Note that the plot file is not deleted unless command arranges to delete it.
  2. file="" or file="|cmd" can be used to print using a pipe on systems that support ‘popen’. Failure to open the command will probably be reported to the terminal but not to ‘popen’, in which case close the device by dev.off immediately.

Only the first of these will work on Windows, and the default "printcmd" is empty and will give an error if print.it=TRUE is used. Suitable commands to spool a PostScript file to a printer can be found in ‘RedMon’ suite available from http://www.cs.wisc.edu/~ghost/index.html. The command will be run in a minimized window. GSView 4.x provides ‘gsprint.exe’ which may be even more convenient (it requires GhostScript version 6.0 or later).

The file argument is interpreted as a C integer format as used by sprintf, with integer argument the page number. The default gives files ‘Rplot001.ps’, ..., ‘Rplot999.ps’, ‘Rplot1000.ps’, ....

The postscript produced for a single R plot is EPS (Encapsulated PostScript) compatible, and can be included into other documents, e.g., into LaTeX, using \includegraphics{<filename>}. For use in this way you will probably want to set horizontal = FALSE, onefile = FALSE, paper = "special". Note that the bounding box is for the device region: if you find the white space around the plot region excessive, reduce the margins of the figure region via par(mar=).

Most of the PostScript prologue used is taken from the R character vector .ps.prolog. This is marked in the output, and can be changed by changing that vector. (This is only advisable for PostScript experts: the standard version is in namespace:grDevices.)

A PostScript device has a default family, which can be set by the user via family. If other font families are to be used when drawing to the PostScript device, these must be declared when the device is created via fonts; the font family names for this argument are R graphics font family names (see the documentation for postscriptFonts).

Line widths as controlled by par(lwd=) are in multiples of 1/96 inch: nultiples less than 1 are allowed. pch="." with cex = 1 corresponds to a square of side 1/72 inch.

Families

Font families are collections of fonts covering the five font faces, (conventionally plain, bold, italic, bold-italic and symbol) selected by the graphics parameter par(font=) or the grid parameter gpar(fontface=). Font families can be specified either as an an initial/default font family for the device via the family argument or after the device is opened by the graphics parameter par(family=) or the grid parameter gpar(fontfamily=). Families which will be used in addition to the initial family must be specified in the fonts argument when the device is opened.

Font families are declared via a call to postscriptFonts.

The argument family specifies the initial/default font family to be used. In normal use it is one of "AvantGarde", "Bookman", "Courier", "Helvetica", "Helvetica-Narrow", "NewCenturySchoolbook", "Palatino" or "Times", and refers to the standard Adobe PostScript fonts families of those names which are included (or cloned) in all common PostScript devices.

Many PostScript emulators (including those based on ghostscript) use the URW equivalents of these fonts, which are "URWGothic", "URWBookman", "NimbusMon", "NimbusSan", "NimbusSanCond", "CenturySch", "URWPalladio" and "NimbusRom" respectively. If your PostScript device is using URW fonts, you will obtain access to more characters and more appropriate metrics by using these names. To make these easier to remember, "URWHelvetica" == "NimbusSan" and "URWTimes" == "NimbusRom" are also supported.

Another type of family makes use of CID-keyed fonts for East Asian languages – see postscriptFonts.

The family argument is normally a character string naming a font family, but family objects generated by Type1Font and CIDFont are also accepted. For compatibiility with earlier versions of R, the initial family can also be specified as a vector of four or five afm files.

Encodings

Encodings describe which glyphs are used to display the character codes (in the range 0–255). Most commonly R uses ISOLatin1 encoding, and the examples for text are in that encoding. However, the encoding used on machines running R may well be different, and by using the encoding argument the glyphs can be matched to encoding in use. This suffices for European and Cyrillic languages, but not for CJK languages. For the latter, composite CID fonts are used. These fonts are useful for other languages: for example they may contain Greek glyphs. (The rest of this section applies only when CID fonts are not used.)

None of this will matter if only ASCII characters (codes 32–126) are used as all the encodings (except "TeXtext") agree over that range. Some encodings are supersets of ISOLatin1, too. However, if accented and special characters do not come out as you expect, you may need to change the encoding. Some other encodings are supplied with R: "WinAnsi.enc" and "MacRoman.enc" correspond to the encodings normally used on Windows and Classic MacOS (at least by Adobe), and "PDFDoc.enc" is the first 256 characters of the Unicode encoding, the standard for PDF. There are also encodings "ISOLatin2.enc", "CP1250.enc", "ISOLatin7.enc" (ISO 8859-13), "CP1257.enc", and "ISOLatin9.enc" (ISO 8859-15), "Cyrillic.enc" (ISO 8859-5), "KOI8-R.enc", "KOI8-U.enc", "CP1251.enc", "Greek.enc" (ISO 8859-7) and "CP1253.enc". Note that many glyphs in these encodings are not in the fonts corresponding to the standard families. (The Adobe ones for all but Courier, Helvetica and Times cover little more than Latin-1, whereas the URW ones also cover Latin-2, Latin-7, Latin-9 and Cyrillic but no Greek. The Adobe exceptions cover the Latin character sets, but not the Euro.)

If you specify the encoding, it is your responsibility to ensure that the PostScript font contains the glyphs used. One issue here is the Euro symbol which is in the WinAnsi and MacRoman encodings but may well not be in the PostScript fonts. (It is in the URW variants; it is not in the supplied Adobe Font Metric files.)

There is an exception. Character 45 ("-") is always set as minus (its value in Adobe ISOLatin1) even though it is hyphen in the other encodings. Hyphen is available as character 173 (octal 0255) in all the Latin encodings, Cyrillic and Greek. There are some discrepancies in accounts of glyphs 39 and 96: the supplied encodings (except CP1250 and CP1251) treat these as ‘quoteright’ and ‘quoteleft’ (rather than ‘quotesingle’/‘acute’ and ‘grave’ respectively), as they are in the Adobe documentation.

TeX fonts

TeX has traditionally made use of fonts such as Computer Modern which are encoded rather differently, in a 7-bit encoding. This encoding can be specified by encoding = "TeXtext.enc", taking care that the ASCII characters < > \ _ { } are not available in those fonts.

There are supplied families "ComputerModern" and "ComputerModernItalic" which use this encoding, and which are only supported for postscript (and not pdf). They are intended to use with the Type 1 versions of the TeX CM fonts. It will normally be possible to include such output in TeX or LaTeX provided it is processed with dvips -Ppfb -j0 or the equivalent on your system. (-j0 turns off font subsetting.) When family = "ComputerModern" is used, the italic/bold-italic fonts used are slanted fonts (cmsl10 and cmbxsl10). To use text italic fonts instead, set family = "ComputerModernItalic".

These families use the TeX math italic and symbol fonts for a comprehensive but incomplete coverage of the glyphs covered by the Adobe symbol font in other families. This is achieved by special-casing the postscript code generated from the supplied ‘CM_symbol_10.afm’.

Author(s)

Support for Computer Modern fonts is based on a contribution by Brian D'Urso durso@hussle.harvard.edu.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

postscriptFonts, Devices, {check.options which is called from both ps.options and postscript}.

Examples

## Not run:
# open the file "foo.ps" for graphics output
postscript("foo.ps")
# produce the desired graph(s)
dev.off()              # turn off the postscript device
options(printcmd='redpr -P"\\markov\lw"')
postscript(file=tempfile("Rps."), print.it=TRUE)
# produce the desired graph(s)
dev.off()              # send plot file to the printer
## alternative using GSView 4.x
options(printcmd='/GhostGum/gsview/gsprint -query')

# for URW PostScript devices
postscript("foo.ps", family = "NimbusSan")

## for inclusion in Computer Modern TeX documents, perhaps
postscript("cm_test.eps", width = 4.0, height = 3.0,
           horizontal = FALSE, onefile = FALSE, paper = "special",
           family = "ComputerModern", encoding = "TeXtext.enc")
## The resultant postscript file can be used by dvips -Ppfb -j0.

## To test out encodings, you can use
TestChars <- function(encoding="ISOLatin1", family="URWHelvetica")
{
    postscript(encoding=encoding, family=family)
    par(pty="s")
    plot(c(-1,16), c(-1,16), type="n", xlab="", ylab="",
         xaxs="i", yaxs="i")
    title(paste("Centred chars in encoding", encoding))
    grid(17, 17, lty=1)
    for(i in c(32:255)) {
        x <- i %% 16
        y <- i %/% 16
        points(x, y, pch=i)
    }
    dev.off()
}
## there will be many warnings.  We use URW to get a complete enough
## set of font metrics.
TestChars()
TestChars("ISOLatin2")
TestChars("WinAnsi")
## End(Not run)


PostScript and PDF Font Families

Description

These functions handle the translation of a R graphics font family name to a PostScript or PDF font description, used by the postscript or pdf graphics devices.

Usage

postscriptFonts(...)
pdfFonts(...)

Arguments

... either character strings naming mappings to display, or named arguments specifying mappings to add or change.

Details

If these functions are called with no argument they list all the existing mappings, whereas if they are called with named arguments they add (or change) mappings.

A PostScript or PDF device is created with a default font family (see the documentation for postscript), but it is also possible to specify a font family when drawing to the device (for example, see the documentation for "family" in par and for "fontfamily" in gpar in the grid package).

The font family sent to the device is a simple string name, which must be mapped to a set of PostScript fonts. Separate lists of mappings for postscript and pdf devices are maintained for the current R session and can be added to by the user.

The postscriptFonts and pdfFonts functions can be used to list existing mappings and to define new mappings. The Type1Font and CIDFont functions can be used to create new mappings, when the xxxFonts function is used to add them to the database. See the examples.

Default mappings are provided for four device-independent family names: "sans" for a sans-serif font, "serif" for a serif font, "mono" for a monospaced font, and "symbol" for a symbol font.

Mappings for a number of standard Adobe fonts (and URW equivalents) are also provided: "AvantGarde", "Bookman", "Courier", "Helvetica", "Helvetica-Narrow", "NewCenturySchoolbook", "Palatino" and "Times"; "URWGothic", "URWBookman", "NimbusMon", "NimbusSan" (synonym "URWHelvetica"), "NimbusSanCond", "CenturySch", "URWPalladio" and "NimbusRom" (synonym "URWTimes").

There are also mappings for "ComputerModern" and "ComputerModernItalic".

Finally, there are some default mappings for East Asian locales described in a separate section.

The specification of font metrics and encodings is described in the help for the postscript function.

The fonts are not embedded in the resulting PostScript or PDF file, so software including the PostScript or PDF plot file should either embed the font outlines (usually from ‘.pfb’ or ‘.pfa’ files) or use DSC comments to instruct the print spooler or including application to do so (see also embedFonts).

A font family has both an R-level name, the argument name used when postscriptFonts was called, and an internal name, the family component. These two names are the same for all the pre-defined font families.

Once a font family is in use it cannot be changed. ‘In use’ means that it has been specified via a family or fonts argument to an invocation of the same graphics device already in the R session. (For these purposes xfig counts the same as postscript but only uses some of the predefined mappings.)

Value

A list of one or more font mappings.

East Asian fonts

There are some default mappings for East Asian locales:
"Japan1", "Japan1HeiMin", "Japan1GothicBBB", and "Japan1Ryumin" for Japanese; "Korea1" and "Korea1deb" for Korean; "GB1" (Simplified Chinese) for mainland China and Singapore; "CNS1" (Traditional Chinese) for Hong Kong and Taiwan.

These refer to the following fonts
Japan1 (PS) | HeiseiKakuGo-W5
 | Linotype Japanese printer font
Japan1 (PDF) | KozMinPro-Regular-Acro
 | from Adobe Reader 7.0 Japanese Font Pack
Japan1HeiMin (PS) | HeiseiMin-W3
 | Linotype Japanese printer font
Japan1HeiMin (PDF) | HeiseiMin-W3-Acro
 | from Adobe Reader 7.0 Japanese Font Pack
Japan1GothicBBB | GothicBBB-Medium
 | Japanese-market PostScript printer font
Japan1Ryumin | Ryumin-Light
 | Japanese-market PostScript printer font
Korea1 (PS) | Baekmuk-Batang
 | TrueType font found on some Linux systems
Korea1 (PDF) | HYSMyeongJoStd-Medium-Acro
 | from Adobe Reader 7.0 Korean Font Pack
Korea1deb (PS) | Batang-Regular
 | another name for Baekmuk-Batang
Korea1deb (PDF) | HYGothic-Medium-Acro
 | from Adobe Reader 4.0 Korean Font Pack
GB1 (PS) | BousungEG-Light-GB
 | TrueType font found on some Linux systems
GB1 (PDF) | STSong-Light-Acro
 | from Adobe Reader 7.0 Simplified Chinese Font Pack
CNS1 (PS) | MOESung-Regular
 | Ken Lunde's CJKV resources
CNS1 (PDF) | MSungStd-Light-Acro
 | from Adobe Reader 7.0 Traditional Chinese Font Pack

Baekmuk-Batang can be found at ftp://ftp.mizi.com/pub/baekmuk/. BousungEG-Light-GB can be found at ftp://ftp.gnu.org/pub/non-gnu/chinese-fonts-truetype/. Ken Lunde's CJKV resources are at ftp://ftp.oreilly.com/pub/examples/nutshell/cjkv/adobe/samples/. These will need to be installed or otherwise made available to the postscript/PDF interpreter such as ghostscript (and not all interpreters can handle TrueType fonts).

You may well find that your postscript/PDF interpreters has been set up to provide aliases for many of these fonts. For example, ghostscript on Windows can optionally be installed to map common CJK fonts names to Windows TrueType fonts. (You may want to add the -Acro versions as well.)

Adding a mapping for a CID-keyed font is for gurus only.

Author(s)

Support for Computer Modern fonts is based on a contribution by Brian D'Urso durso@hussle.harvard.edu.

See Also

postscript and pdf; Type1Font and CIDFont for specifying new font mappings.

Examples

postscriptFonts()
## This duplicates "ComputerModernItalic".
CMitalic <- Type1Font("ComputerModern2",
                      c("CM_regular_10.afm", "CM_boldx_10.afm",
                        "cmti10.afm", "cmbxti10.afm",
                         "CM_symbol_10.afm"),
                      encoding = "TeXtext.enc")
postscriptFonts(CMitalic = CMitalic)

## A CID font for Japanese using a different CMap and
## corresponding cmapEncoding.
`Jp_UCS-2` <- CIDFont("TestUCS2",
                  c("Adobe-Japan1-UniJIS-UCS2-H.afm",
                    "Adobe-Japan1-UniJIS-UCS2-H.afm",
                    "Adobe-Japan1-UniJIS-UCS2-H.afm",
                    "Adobe-Japan1-UniJIS-UCS2-H.afm"),
                  "UniJIS-UCS2-H", "UCS-2")
pdfFonts(`Jp_UCS-2` = `Jp_UCS-2`)
names(pdfFonts())


Auxiliary Function to Set/View Argument of postscript

Description

The auxiliary function ps.options can be used to set and view (if called without arguments) default values for the arguments to postscript.

ps.options needs to be called before calling postscript, and the default values it sets can be overridden by supplying arguments to postscript.

Usage

ps.options(..., reset = FALSE, override.check = FALSE)

Arguments

... | arguments paper, horizontal, width, height, family, encoding, pointsize, bg, fg, onefile, print.it, and append (ignored) can be supplied.
reset, override.check | logical arguments passed to check.options. See the Examples.

Value

A named list of arguments.

See Also

postscript

Examples

ps.options(bg = "pink")
utils::str(ps.options(reset = TRUE))

### ---- error checking of arguments: ----
ps.options(width=0:12, onefile=0, bg=pi)
# override the check for 'onefile', but not the others:
utils::str(ps.options(width=0:12, onefile=1, bg=pi,
                      override.check = c(FALSE,TRUE,FALSE)))


Record graphics operations

Description

Records arbitrary code on the graphics engine display list. Useful for encapsulating calculations with graphical output that depends on the calculations. Intended only for expert use.

Usage

recordGraphics(expr, list, env)

Arguments

expr | object of mode expression or call or an “unevaluated expression”.
list | a list defining the environment in which expr is to be evaluated.
env | An environment specifying where R looks for objects not found in envir.

Details

The code in expr is evaluated in an environment constructed from list, with env as the parent of that environment.

All three arguments are saved on the graphics engine display list so that on a device resize or copying between devices, the original evaluation environment can be recreated and the code can be re-evaluated to reproduce the graphical output.

Value

The value from evaluating expr.

Warning

This function is not intended for general use. Incorrect or improper use of this function could lead to unintended and/or undesirable results.

An example of acceptable use is querying the current state of a graphics device or graphics system setting and then calling a graphics function.

An example of improper use would be calling the assign function to performing assignments in the global environment.

See Also

eval

Examples

plot(1:10)
# This rectangle remains 1inch wide when the device is resized
recordGraphics(
  {
    rect(4, 2,
         4 + diff(par("usr")[1:2])/par("pin")[1], 3)
  },
  list(),
  getNamespace("graphics"))


Record and Replay Plots

Description

Functions to save the current plot in an R variable, and to replay it.

Usage

recordPlot()
replayPlot(x)

Arguments

x A saved plot.

Details

These functions record and replay the displaylist of the current graphics device. The returned object is of class "recordedplot", and replayPlot acts as a print method for that class.

Value

recordPlot returns an object of class "recordedplot".
replayPlot has no return value.

Warning

The format of recorded plots may change between R versions. Recorded plots should not be used as a permanent storage format for R plots.

R will always attempt to replay a recorded plot, but if the plot was recorded with a different R version then bad things may happen.


RGB Color Specification

Description

This function creates “colors” corresponding to the given intensities (between 0 and max) of the red, green and blue primaries.

An alpha transparency value can also be specified (0 means fully transparent and max means opaque). If alpha is not specified, an opaque colour is generated.

The names argument may be used to provide names for the colors.

The values returned by these functions can be used with a col= specification in graphics functions or in par.

Usage

rgb(red, green, blue, alpha, names = NULL, maxColorValue = 1)

Arguments

red, blue, green, alpha | vectors of same length with values in [0, M] where M is maxColorValue. When this is 255, the red, blue, green, and alpha values are coerced to integers in 0:255 and the result is computed most efficiently.
names | character. The names for the resulting vector.
maxColorValue | number giving the maximum of the color values range, see above.

See Also

col2rgb the “inverse” for translating R colors to RGB vectors; rainbow, hsv, hcl, gray.

Examples

rgb(0,1,0)
(u01 <- seq(0,1, length=11))
stopifnot(rgb(u01,u01,u01) == gray(u01))
reds <- rgb((0:15)/15, g=0,b=0, names=paste("red",0:15,sep="."))
reds

rgb(0, 0:12, 0, max = 255)# integer input


RGB to HSV Conversion

Description

rgb2hsv transforms colors from RGB space (red/green/blue) into HSV space (hue/saturation/value).

Usage

rgb2hsv(r, g = NULL, b = NULL, gamma = 1, maxColorValue = 255)

Arguments

r | vector of “red” values in [0,M], (M =maxColorValue) or 3-row rgb matrix.
g | vector of “green” values, or NULL when r is a matrix.
b | vector of “blue” values, or NULL when r is a matrix.
gamma | a “gamma correction” (supposedly applied to the r,g,b values previously), see hsv(...., gamma).
maxColorValue | number giving the maximum of the RGB color values range. The default 255 corresponds to the typical 0:255 RGB coding as in col2rgb().

Details

Value (brightness) gives the amount of light in the color.
Hue describes the dominant wavelegth.
Saturation is the amount of Hue mixed into the color.

Value

A matrix with a column for each color. The three rows of the matrix indicate hue, saturation and value and are named "h", "s", and "v" accordingly.

Author(s)

R interface by Wolfram Fischer wolfram@fischer-zim.ch;
C code mainly by Nicholas Lewin-Koh nikko@hailmail.net.

See Also

hsv, col2rgb, rgb.

Examples

## These (saturated, bright ones) only differ by hue
(rc <- col2rgb(c("red", "yellow","green","cyan", "blue", "magenta")))
(hc <- rgb2hsv(rc))
6 * hc["h",] # the hues are equispaced

(rgb3 <- floor(256 * matrix(runif(3*12), 3,12)))
(hsv3 <- rgb2hsv(rgb3))
## Consistency :
stopifnot(rgb3 == col2rgb(hsv(h=hsv3[1,], s=hsv3[2,], v=hsv3[3,])),
          all.equal(hsv3, rgb2hsv(rgb3/255, maxC = 1)))

## A (simplified) pure R version -- originally by Wolfram Fischer --
## showing the exact algorithm:
rgb2hsvR <- function(rgb, gamma = 1, maxColorValue = 255)
{
    if(!is.numeric(rgb)) stop("rgb matrix must be numeric")
    d <- dim(rgb)
    if(d[1] != 3) stop("rgb matrix must have 3 rows")
    n <- d[2]
    if(n == 0) return(cbind(c(h=1,s=1,v=1))[,0])
    rgb <- rgb/maxColorValue
    if(gamma != 1) rgb <- rgb ^ (1/gamma)

    ## get the max and min
    v <- apply( rgb, 2, max)
    s <- apply( rgb, 2, min)
    D <- v - s # range

    ## set hue to zero for undefined values (gray has no hue)
    h <- numeric(n)
    notgray <- ( s != v )

    ## blue hue
    idx <- (v == rgb[3,] & notgray )
    if (any (idx))
        h[idx] <- 2/3 + 1/6 * (rgb[1,idx] - rgb[2,idx]) / D[idx]
    ## green hue
    idx <- (v == rgb[2,] & notgray )
    if (any (idx))
        h[idx] <- 1/3 + 1/6 * (rgb[3,idx] - rgb[1,idx]) / D[idx]
    ## red hue
    idx <- (v == rgb[1,] & notgray )
    if (any (idx))
        h[idx] <-       1/6 * (rgb[2,idx] - rgb[3,idx]) / D[idx]

    ## correct for negative red
    idx <- (h < 0)
    h[idx] <- 1+h[idx]

    ## set the saturation
    s[! notgray] <- 0;
    s[notgray] <- 1 - s[notgray] / v[notgray]

    rbind( h=h, s=s, v=v )
}

## confirm the equivalence:
all.equal(rgb2hsv (rgb3),
          rgb2hsvR(rgb3), tol=1e-14) # TRUE


Save Windows Plot to a File

Description

Saves the current plot on a windows device to a file.

Usage

savePlot(filename = "Rplot",
         type = c("wmf", "emf", "png", "jpeg", "jpg", "bmp",
                  "ps", "eps", "pdf"),
         device = dev.cur(),
         restoreConsole = TRUE)

Arguments

filename | The filename under which to save the plot, without the extension.
type | The type of plot, Windows metafile, PNG, JPEG, BMP (Windows bitmap format), PostScript or PDF.
device | A device number of a windows device, by default the current device.
restoreConsole | See the Details section of windows.

Details

This is equivalent to selecting the ‘Save as’ menu item on the ‘File’ menu of a windows device.

Using filename as "clipboard" or "" with type = "wmf" will copy to the clipboard.

Types "eps" and "ps" are the same thing apart from the extension. Similarly "wmf"/"emf" and "jpeg"/"jpg".

Value

None, but a plot file will be created.

See Also

windows, dev.print


3D to 2D Transformation for Perspective Plots

Description

Projection of 3-dimensional to 2-dimensional points using a 4x4 viewing transformation matrix. Mainly for adding to perspective plots such as persp.

Usage

trans3d(x,y,z, pmat)

Arguments

x, y, z | numeric vectors of equal length, specifying points in 3D space.
pmat | a 4 x 4 viewing transformation matrix, suitable for projecting the 3D coordinates (x,y,z) into the 2D plane using homogenous 4D coordinates (x,y,z,t); such matrices are returned by persp().

Value

a list with two components

x,y the projected 2d coordinates of the 3d input (x,y,z).

See Also

persp

Examples

## See  help(persp) {after attaching the 'graphics' package}
##      -----------


Type 1 and CID Fonts

Description

These functions are used to define the translation of a R graphics font family name to a Type 1 or CID font descriptions, used by both the postscript and pdf graphics devices.

Usage

Type1Font(family, metrics, encoding = "default")

CIDFont(family, cmap, cmapEncoding, pdfresource = "")

Arguments

family | a character string giving the name to be used internally for a Type 1 or CID-keyed font family. This needs to uniquely identify each family, so if you modify a family which is in use (see postscriptFonts) you need to change the family name.
metrics | a character vector of four or five strings giving paths to the afm (Adobe Font Metric) files for the font.
cmap | the name of a CMap file for a CID-keyed font.
encoding | for Type1Font, the name of an encoding file. Defaults to "default", which maps on this platform to "WinAnsi.enc". Otherwise, a file name in the ‘enc’ directory of the grDevices package, which is used if the path does not contain a path separator. An extension ".enc" can be omitted.
cmapEncoding | The name of a charset encoding to be used with the named CMap file: strings will be translated to this encoding when written to the file.
pdfresource | A chunk of PDF code; only required for using a CID-keyed font on pdf; users should not be expected to provide this.

Details

For Type1Fonts, if four .afm files are supplied the fifth is taken to be "Symbol.afm". Relative paths are taken relative to the directory ‘R_HOME/library/grDevices/afm’. The fifth (symbol) font must be in AdobeSym encoding. However, the glyphs in the first four fonts are referenced by name and any encoding given within the .afm files is not used.

Glyphs in CID-keyed fonts are accessed by ID (number) and not by name. The CMap file maps encoded strings (usually in a MBCS) to IDs, so cmap and cmapEncoding specifications must match. There are no real bold or italic versions of CID fonts (bold/italic were very rarely used in traditional CJK topography), and for the pdf device all four font faces will be identical. However, for the postscript device, bold and italic (and bold italic) are emulated.

CID-keyed fonts are intended only for use for the glyphs of CJK languages, which are all monospaced and are all treated as filling the same bounding box. (Thus plotmath will work with such characters, but the spacing will be less carefully controlled than with Western glyphs.) The CID-keyed fonts do contain other characters, including a Latin alphabet: non-CJK glyphs are regarded as monospaced with half the width of CJK glyphs. This is often the case, but sometimes Latin glyphs designed for proportional spacing are used (and may look odd). We strongly recommend that CID-keyed fonts are only used for CJK glyphs.

Value

A list of class "Type1Font" or "CIDFont".

See Also

postscript, pdf, postscriptFonts, and pdfFonts.

Examples

## This duplicates "ComputerModernItalic".
CMitalic <- Type1Font("ComputerModern2",
                      c("CM_regular_10.afm", "CM_boldx_10.afm",
                        "cmti10.afm", "cmbxti10.afm",
                        "CM_symbol_10.afm"),
                      encoding = "TeXtext.enc")

## Not run:
## This could be used by
postscript(family = CMitalic)
## or
postscriptFonts(CMitalic = CMitalic)  # once in a session
postscript(family = "CMitalic", encoding = "TeXtext.enc")
## End(Not run)


Windows graphics devices

Description

A graphics device is opened. For windows, win.graph, x11 and X11 this is a graphics window on the current Windows display: the multiple names are for compatibility with other systems. win.metafile prints to a file and win.print to the Windows print system.

Usage

windows(width = 7, height = 7, pointsize = 12,
        record = getOption("graphics.record"),
        rescale = c("R", "fit", "fixed"), xpinch, ypinch,
        bg = "transparent", canvas = "white",
        gamma = getOption("gamma"), xpos = NA, ypos = NA,
        buffered = getOption("windowsBuffered"),
        restoreConsole = FALSE)

win.graph(width = 7, height = 7, pointsize = 12,
          restoreConsole = FALSE)
x11(width = 7, height = 7, pointsize = 12, restoreConsole = FALSE)
X11(width = 7, height = 7, pointsize = 12, restoreConsole = FALSE)

win.metafile(filename = "", width = 7, height = 7, pointsize = 12,
             restoreConsole = TRUE)

win.print(width = 7, height = 7, pointsize = 12, printer = "",
          restoreConsole = TRUE)

Arguments

width, height | the (nominal) width and height of the canvas of the plotting window in inches.
pointsize | the default pointsize of plotted text. Values are rounded to the nearest integer: values less than or equal to zero are reset to 12.
record | logical: sets the initial state of the flag for recording plots.
rescale | controls the action for resizing plots.
xpinch, ypinch | double. Pixels per inch, horizontally and vertically.
bg | color. The default background color.
canvas | color. The color of the canvas which is visible when the background color is transparent.
gamma | the gamma correction factor. This value is used to ensure that the colors perceived are linearly related to RGB values (see hsv). By default this is taken from options("gamma"), or is 1 (no correction) if that is unset (the usual case).
xpos, ypos | integer. Position of the top left of the window, in pixels. Negative values are taken from the opposite edge of the monitor. Missing values meant take the default from the ‘Rconsole’ file, which in turn defaults to xpos=-25, ypos=0: this puts the right edge of the window 25 pixels from the right edge of the monitor.
buffered | logical. Should the screen output be double-buffered?
filename | the name of the output file: it will be an enhanced Windows metafile, usually given extension .emf or .wmf. Up to 511 characters are allowed. The page number is substituted if an integer format is included in the character string. (The result must be less than 600 characters long.) The default, "", means the clipboard.
printer | The name of a printer as known to Windows. The default causes a dialog box to come for the user to choose a printer.
restoreConsole | logical: see the Details below.

Details

All these devices are implemented as windows devices, the display parameter selects which is actually used.

The size of a window is computed from information provided about the display: it depends on the system being configured accurately. By default a screen device asks Windows for the number of pixels per inch. This can be overridden (it is often wrong) by specifying xpinch and ypinch or the corresponding options "xpinch" and "ypinch".

A graphics window is not allowed to be specified at more that 85% of the screen width or height: the width and height are rescaled proportionally. The window can be resized to a larger size. In MDI mode, the limit is 85% of the MDI client region.

If the filename is omitted for a win.metafile device, the output is copied to the clipboard when the device is closed.

If a screen device is re-sized, the default behaviour is to redraw the plot(s) as if the new size had been specified originally. Using "fit" will rescale the existing plot(s) to fit the new device region, preserving the aspect ratio. Using "fixed" will leave the plot size unchanged, adding scrollbars if part of the plot is obscured.

A graphics window will never be created at more that 85% of the screen width or height, but can be resized to a larger size. For the first two rescale options the width and height are rescaled proportionally if necessary, and if rescale = "fit" the plot(s) are rescaled accordingly. If rescale = "fixed" the initially displayed portion is selected within these constraints, separately for width and height.

Using strwidth or strheight after a window has been rescaled (when using "fit") gives dimensions in the original units, but only approximately as they are derived from the metrics of the rescaled fonts (which are in integer sizes)

The displayed region may be bigger than the ‘paper’ size, and areas outside the ‘paper’ are coloured in the Windows application background colour. Graphics parameters such as "din" refer to the scaled plot if rescaling is in effect.

The different colours need to be distinguished carefully. The area outside the device region is coloured in the Windows application background colour. The device region is coloured in the canvas colour. This is over-painted by the background colour of a plot when a new page is called for, but that background colour can be transparent (and is by default). The difference between setting the canvas colour and the background colour is that when the device is copied the background colour is copied but the canvas colour is not.

Recorded plot histories are of class "SavedPlots". They have a print method, and a subset method. As the individual plots are of class "recordedplot" they can be replayed by printing them: see recordPlot. The active plot history is stored in variable .SavedPlots in the workspace.

When a screen device is double-buffered (the default) the screen is updated 100ms after last plotting call or every 500ms during continuous plotting. These times can be altered by setting options("windowsTimeout") to a vector of two integers before opening the device.

The font used for text drawn in a Windows device may be controlled in two ways. The file RHOME\etc\Rdevga can be used to specify mappings for par(font=) (in the graphics package). Alternatively, a device-independent R graphics font family can be specified (e.g., via par(family=) in the graphics package) and this will be mapped via the Windows font database (see windowsFonts).

Line widths as controlled by par(lwd=) are in multiples of 1/96inch. Multiples less than 1 are allowed, down to one pixel width.

pch="." with cex = 1 corresponds to a rectangle of sides the larger of one pixel and 0.01 inch.

For win.metafile only one plot is allowed per file, and Windows seems to disallow reusing the file. So the only way to allow multiple plots is to use a parametrized filename as in the example.

The restoreConsole argument is a temporary fix for a problem in the current implementation of several Windows graphics devices, and is likely to be removed in an upcoming release. If set to FALSE, the console will not receive the focus after the new device is opened.

Value

A plot device is opened: nothing is returned to the R interpreter.

See Also

windowsFonts, savePlot, bringToTop, Devices, postscript

Examples

## Not run:
## A series of plots written to a sequence of metafiles
win.metafile("Rplot%02d.wmf", pointsize = 10)
## End(Not run)


Windows Fonts

Description

These functions handle the translation of a device-independent R graphics font family name to a windows font description.

Usage

windowsFont(family)

windowsFonts(...)

Arguments

family | a character vector containing the font family name ("TT" as the first two characters indicates a TrueType font).
... | either character strings naming mappings to display, or new (named) mappings to define.

Details

A windows device is created with a default font (see the documentation for windows), but it is also possible to specify a font family when drawing to the device (for example, see the documentation for gpar in the grid package).

The font family sent to the device is a simple string name, which must be mapped to something more specific to windows fonts. A list of mappings is maintained and can be modified by the user.

The windowsFonts function can be used to list existing mappings and to define new mappings. The windowsFont function can be used to create a new mapping.

Default mappings are provided for four device-independent font family names: "sans" for a sans-serif font, "serif" for a serif font, "mono" for a monospaced font, and "symbol" for a symbol font.

These mappings will only be used if the current font face is 1 (plain), 2 (bold), 3 (italic), or 4 (bolditalic).

See Also

windows

Examples

windowsFonts()
windowsFonts("mono")

## Not run:
## set up for Japanese: needs an East Asian locale
windows()  # make sure we have the right device type
Sys.setlocale("LC_ALL", "ja")
windowsFonts(JP1 = windowsFont("MS Mincho"),
             JP2 = windowsFont("MS Gothic"),
             JP3 = windowsFont("Arial Unicode MS"))
plot(1:10)
text(5, 2, "\u{4E10}\u{4E00}\u{4E01}", family = "JP1")
text(7, 2, "\u{4E10}\u{4E00}\u{4E01}", family = "JP1", font=2)
text(5, 1.5, "\u{4E10}\u{4E00}\u{4E01}", family = "JP2")
text(9, 2, "\u{5100}", family = "JP3")
## End(Not run)


XFig Graphics Device

Description

xfig starts the graphics device driver for producing XFig (version 3.2) graphics.

The auxiliary function ps.options can be used to set and view (if called without arguments) default values for the arguments to xfig and postscript.

Usage

xfig(file = ifelse(onefile, "Rplots.fig", "Rplot%03d.fig"),
     onefile = FALSE, encoding = "none", ...)

Arguments

file | a character string giving the name of the file. For use with onefile = FALSE give a C integer format such as "Rplot%03d.fig" (the default in that case). (See postscript for further details.)
onefile | logical: if true allow multiple figures in one file. If false, assume only one page per file and generate a file number containing the page number.
encoding | The encoding in which to write text strings. The default is not to re-encode. This can be any encoding recognized by iconv: in a Western UTF-8 locale you probably want to select an 8-bit encoding such as latin1, and in an East Asian locale an EUC encoding. If re-encoding fails, the text strings will be written in the current encoding with a warning.
... further arguments to ps.options accepted by xfig():
paper
the size of paper in the printer. The choices are "A4", "Letter" and "Legal" (and these can be lowercase). A further choice is "default", which is the default. If this is selected, the papersize is taken from the option "papersize" if that is set and to "A4" if it is unset or empty.
horizontal
the orientation of the printed image, a logical. Defaults to true, that is landscape orientation.
width, height
the width and height of the graphics region in inches. The default is to use the entire page less a 0.25 inch border.
family
the font family to be used. This must be one of "AvantGarde", "Bookman", "Courier", "Helvetica", "Helvetica-Narrow", "NewCenturySchoolbook", "Palatino" or "Times". Any other value is replaced by "Helvetica" with a warning.
pointsize
the default point size to be used.
bg
the default background color to be used.
fg
the default foreground color to be used.
pagecentre
logical: should the device region be centred on the page: defaults to TRUE.

Details

Although xfig can produce multiple plots in one file, the XFig format does not say how to separate or view them. So onefile = FALSE is the default.

The file argument is interpreted as a C integer format as used by sprintf, with integer argument the page number. The default gives files ‘Rplot001.fig’, ..., ‘Rplot999.fig’, ‘Rplot1000.fig’, ....

Line widths as controlled by par(lwd=) are in multiples of 5/6*1/72 inch. Multiples less than 1 are allowed. pch="." with cex = 1 corresponds to a square of side 1/72 inch.

Windows users can make use of WinFIG (http://www.schmidt-web-berlin.de/WinFIG.htm).

Note

Only some line textures (0 <= lty < 4) are used. Eventually this will be partially remedied, but the XFig file format does not allow as general line textures as the R model. Unimplemented line textures are displayed as dash-double-dotted.

There is a limit of 512 colours (plus white and black) per file.

See Also

Devices, postscript, ps.options.


Extracting Plotting Structures

Description

xy.coords is used by many functions to obtain x and y coordinates for plotting. The use of this common mechanism across all relevant R functions produces a measure of consistency.

Usage

xy.coords(x, y = NULL, xlab = NULL, ylab = NULL, log = NULL,
          recycle = FALSE)

Arguments

x, y | the x and y coordinates of a set of points. Alternatively, a single argument x can be provided.
xlab,ylab | names for the x and y variables to be extracted.
log | character, "x", "y" or both, as for plot. Sets negative values to NA and gives a warning.
recycle | logical; if TRUE, recycle (rep) the shorter of x or y if their lengths differ.

Details

An attempt is made to interpret the arguments x and y in a way suitable for bivariate plotting (or other bivariate procedures).

If y is NULL and x is a

formula:
of the form yvar ~ xvar. xvar and yvar are used as x and y variables.
list:
containing components x and y, these are used to define plotting coordinates.
time series:
the x values are taken to be time(x) and the y values to be the time series.
matrix or data.frame with two or more columns:
the first is assumed to contain the x values and the second the y values. Note that is also true if x has columns named "x" and "y"; these names will be irrelevant here.

In any other case, the x argument is coerced to a vector and returned as y component where the resulting x is just the index vector 1:n. In this case, the resulting xlab component is set to "Index".

If x (after transformation as above) inherits from class "POSIXt" it is coerced to class "POSIXct".

Value

A list with the components

x | numeric (i.e., "double") vector of abscissa values.
y | numeric vector of the same length as x.
xlab | character(1) or NULL, the ‘label’ of x.
ylab | character(1) or NULL, the ‘label’ of y.

See Also

plot.default, lines, points and lowess are examples of functions which use this mechanism.

Examples

xy.coords(stats::fft(c(1:10)), NULL)

with(cars, xy.coords(dist ~ speed, NULL)$xlab ) # = "speed"

xy.coords(1:3, 1:2, recycle=TRUE)
xy.coords(-2:10,NULL, log="y")
##> warning: 3 y values <=0 omitted ..


Extracting Plotting Structures

Description

Utility for obtaining consistent x, y and z coordinates and labels for three dimensional (3D) plots.

Usage

xyz.coords(x, y = NULL, z = NULL, xlab = NULL, ylab = NULL, zlab = NULL,
           log = NULL, recycle = FALSE)

Arguments

x, y, z | the x, y and z coordinates of a set of points. Both y and z can be left at NULL. In this case, an attempt is made to interpret x in a way suitable for plotting. If the argument is a formula zvar ~ xvar + yvar, xvar, yvar and zvar are used as x, y and z variables; if the argument is a list containing components x, y and z, these are assumed to define plotting coordinates; if the argument is a matrix or data.frame with three or more columns, the first is assumed to contain the x values, the 2nd the y ones, and the 3rd the z ones – independently of any column names that x may have. Alternatively two arguments x and y can be provided (leaving z = NULL). One may be real, the other complex; in any other case, the arguments are coerced to vectors and the values plotted against their indices.
xlab, ylab, zlab | names for the x, y and z variables to be extracted.
log | character, "x", "y", "z" or combinations. Sets negative values to NA and gives a warning.
recycle | logical; if TRUE, recycle (rep) the shorter ones of x, y or z if their lengths differ.

Value

A list with the components

x | numeric (i.e., double) vector of abscissa values.
y | numeric vector of the same length as x.
z | numeric vector of the same length as x.
xlab | character(1) or NULL, the axis label of x.
ylab | character(1) or NULL, the axis label of y.
zlab | character(1) or NULL, the axis label of z.

Author(s)

Uwe Ligges and Martin Maechler

See Also

xy.coords for 2D.

Examples

xyz.coords(data.frame(10*1:9, -4), y = NULL, z = NULL)

xyz.coords(1:6, stats::fft(1:6), z = NULL, xlab = "X", ylab = "Y")

y <- 2 * (x2 <- 10 + (x1 <- 1:10))
xyz.coords(y ~ x1 + x2, y = NULL, z = NULL)

xyz.coords(data.frame(x = -1:9, y = 2:12, z = 3:13), y = NULL, z = NULL,
           log = "xy")
##> Warning message: 2 x values <= 0 omitted ...