Sei sulla pagina 1di 28

R

Graphics

R.M. Ripley

Department of Statistics
University of Oxford

2012/13

R.M. Ripley (University of Oxford) R 2012/13 1 / 28


Graphics

Graphics

We will cover two different types of graphics: base and


lattice.

Many classes of objects have plot methods defined, e.g. lm,


so plot() can give different results with different objects.

Plots usually appear in a window, opened automatically when


necessary. Sometimes useful to open one explicitly using
dev.new() so you can customise it, or have two open at
once.

R.M. Ripley (University of Oxford) R 2012/13 2 / 28


Graphics

Recording, saving, and printing plots

On Windows, can record plots so you can revisit them. Option


on History Menu. Beware: if there are many plots, and you
want to save the remainder of your workspace, clear the
history first. (R can have difficulty reloading .RData files
which contain many large saved plots.)

Can save or print plot from the graphics window menu (not
Unix), or open special device such as pdf, run the plot and
then close the device using dev.off(). e.g.
pdf("myfile.pdf")
plot(1:10)
dev.off()

Recommended to save plots using a special device: can


control scaling better.

R.M. Ripley (University of Oxford) R 2012/13 3 / 28


Graphics Base Graphics

Base Graphics

Base Graphics are


Simpler to use than lattice graphics

Build up piece by piece

Use function such as plot, barplot, contour to


create basic plot then add extra points, lines, legends etc.

R.M. Ripley (University of Oxford) R 2012/13 4 / 28


Graphics Base Graphics

Line and scatter plots

plot() produces scatter-type plots of a numeric vector y against


another, x, or x against index, or a function of one variable
between some limits.

Ways to call the function


plot(x) ## plots against 1:length(x)
plot(x, y)
plot(list(x=x, y=y))
plot(cbind(x, y))
plot(sin, -pi, pi)
plot(y ~ x, data=mydata)
Note arguments are reversed
use of data= argument is supported.

R.M. Ripley (University of Oxford) R 2012/13 5 / 28


Graphics Base Graphics

Plot types

The type argument controls how the points or lines are drawn.
The main options are:
type="p" plots points
type="l" plots a line (the data must be in the correct order!)
type="n" plots nothing,just creates the axes for later use
type="b" plots both lines and points, lines miss the points
type="o" plot overlaid lines and points
type="h" plots histogram-like vertical lines
type="s" plots step-like lines

R.M. Ripley (University of Oxford) R 2012/13 6 / 28


Graphics Base Graphics

Plot: other arguments

Commonly used arguments to this function include


axes=FALSE suppresses axes
xlab="string" label for x-axis, default: name of variable
ylab="string" label for y-axis, default: name of variable
sub="string" subtitle to appear under the x-axis, default: empty
main="string" title to appear at top of plot, default: empty
xlim=c(lo, hi) Approximate values for range of axes. Will
ylim=c(lo, hi) normally be automatically rounded.

R.M. Ripley (University of Oxford) R 2012/13 7 / 28


Graphics Base Graphics

Adding lines, points etc. to plots


In these commands, except the last, specify the points to use as for
plot().
points() adds points to a plot.

Plotting characters are selected by the graphical parameter


pch. For details see pch in help(points) and
example(points)

lines() adds lines to plot. Line type can be specified by


lty=n. For values see lty in help(par).

text(..., labels) adds labels, vector of integers or


character strings, to a plot at the points specified.

abline() adds lines to a plot. Specify by intercept and slope,


or h=c or v=c for horizontal or vertical.
R.M. Ripley (University of Oxford) R 2012/13 8 / 28
Graphics Base Graphics

Enhancing the plots: use of par


More control of the plots: use graphics parameters. Use par
command or add to call to plot.
Shape: selected by pty.
pty="s" for square region, pty="m" for maximal region.
Size of text and symbols: controlled by cex. If set in a call to
par this is an absolute value, if set in call to plot or points
it is a scaling factor for the current value.
Layout of multiple plots on one screen can be specified by
mfrow:
par(mfrow=c(2, 3))
will give a 2 × 3 array of figures, filled by rows. ( Alternative
ways to specify layout: screen.split and layout.)
The parameter col can be used to specify colour. For details
see the entry for col in help(par).
Examples in demo 4.1.
R.M. Ripley (University of Oxford) R 2012/13 9 / 28
Graphics Base Graphics

Adding legends to plots

Use legend(x, y, legend,...) function.

Specify location by giving upper left corner of box or both


upper left and lower right corners, or by keyword e.g.
"topleft".

Often convenient to find placing by locator(1) or


locator(2). (see later).

Argument legend is character vector of labels.

Remaining arguments are vectors of same length as legend,


giving coding for each variation. e.g. lty=, lwd=, col=,
fill=, angle=, density=, pch=
Examples in demo 4.2

R.M. Ripley (University of Oxford) R 2012/13 10 / 28


Graphics Base Graphics

Identifying points interactively


locator(n, type) returns the coordinates of up to n points on
a plot where mouse button is clicked.
Useful to find coordinates for placing legends. e.g.
legend(locator(1), legend,...)

If type is specified points and/or lines will be plotted.

Terminate early by
clicking the middle mouse button (if present (or wheel!))
right-clicking and selecting Stop
selecting Stop from the graphics menu.

Not a good idea to use locator if you have a set of


commands you wish to run non-interactively.

R.M. Ripley (University of Oxford) R 2012/13 11 / 28


Graphics Base Graphics

Identifying points interactively

identify() allows placement of labels at points on a plot.


Create the plot first.
Then use identify(x,y,labels) with x,y the points you
might wish to identify. Default labels are 1 : n.
Label is placed at point of plot nearest mouse click.
For greater control over label, use identify() without labels.
Plot using text with the coordinates of the points returned.
Terminate by
Selecting all the points
clicking the middle mouse button (if present (or wheel!))
right-clicking and selecting Stop
selecting Stop from the graphics menu.

R.M. Ripley (University of Oxford) R 2012/13 12 / 28


Graphics Base Graphics

Other types of plot


Not covered in detail here: lattice versions are often better.
barplot() produces a bar chart. Specify the bars by a
vector of heights, or a matrix whose columns define the
subdivided bars.
boxplot() produces a box-and-whisker plot. Specify data by
a formula, or two vectors.
pie() produces a pie diagram
pairs() produces a grid of scatter plots. Specify data as a
matrix, columns of a data frame (logical and factor will be
converted to numeric), or by formula ~x+y+z,data=
contour(), persp(), image() allow the display of a
function defined on a 2-dimensional grid.
Examples in demo 4.3
R.M. Ripley (University of Oxford) R 2012/13 13 / 28
Graphics Base Graphics

Mathematics in labels

Can use subscripts, superscripts etc. in text on plots.


e.g. xlab=expression(hat(beta)ˆ2)
will label the x-axis βˆ2 .
For details, help(plotmath) or demo(plotmath).
Can be used in lattice plots too.
Examples in demo 4.4

R.M. Ripley (University of Oxford) R 2012/13 14 / 28


Graphics Lattice Graphics

Lattice Graphics

Remember to load package lattice.


Usually create a plot all in one command, rather than piece by
piece.
Commands create a trellis object which is printed unless
the object has been assigned to a variable.
To place multiple graphs on one screen, create them all first
then print them in the required layout.
Can use update to create a new plot from a previous
trellis object.
trellis.focus allows return to a plotted graph to add extra
features.

R.M. Ripley (University of Oxford) R 2012/13 15 / 28


Graphics Lattice Graphics

Lattice Graphics

Most common functions are: xyplot, bwplot,


stripplot, dotplot, barchart.
Specify data as a formula: ~ x, y ~ x, or z ~ x + y as
appropriate
Can use data=, subset=.
The argument groups= may be used to split the data into
groups before plotting, typically using different colors or
characters to distinguish the groups.
Most useful help page is that for xyplot
Examples in demo 4.5

R.M. Ripley (University of Oxford) R 2012/13 16 / 28


Graphics Lattice Graphics

Panel functions

Extra lines etc. are added by means of panel functions.


Build up your panel function from functions provided e.g.
panel=function(x, y, ...)
{
panel.xyplot(x, y, ...)
panel.lmline(x, y, type="l")
panel.abline(lqs(y ~ x), lty=3)
}
The function is called with the points as arguments.
If groups is used, a vector of subgroup indices is added to the
arguments.
Consult help pages for panel.functions for details of
available functions.
Examples in demo 4.6
R.M. Ripley (University of Oxford) R 2012/13 17 / 28
Graphics Lattice Graphics

Conditioning plots
Can create a set of panels in one plot, with each panel
corresponding to a subset of the data defined by conditioning
variables.
specify the conditioning variables in the formula after a |,
separated by *
The panel function is called once for each panel, with
appropriate points, and an argument subscripts, indices of
the points in the input data.
Conditioning numeric variables will be converted to shingles
(overlapping factors), but default is to use all the unique
values. Use equal.count(x) for fewer groups. e.g.
Cath <- equal.count(swiss$Catholic)
xyplot(Fertility ~ Education | Cath,
data=swiss)
Examples in demo 4.7
R.M. Ripley (University of Oxford) R 2012/13 18 / 28
Graphics Lattice Graphics

Conditioning plots: appearance

Style of strip labels can be altered by using e.g.


strip=strip.custom(style=2)
style= can take values 1 to 5. Try them out. Alters placement
of text and colour of strip labels. Not used for shingles.
strip.levels= is a vector of 2 logical variables, indicating
whether the current level of the conditioning variable should be
shown. First entry for factors, second for shingles. (If only one,
will be used for both.)
strip.names is also a vector of 2 logical variables, indicating
whether the name of the conditioning variable should be
shown. First entry for factors, second for shingles.
Use argument layout=c(c, r, p) to control arrangement
of grid in c columns of r rows on p pages. Can omit p.
Examples in demo 4.8

R.M. Ripley (University of Oxford) R 2012/13 19 / 28


Graphics Lattice Graphics

Lattice plots: legends


The argument key allows great flexibility but is complicated to
use.
The argument auto.key can be set to TRUE to produce a
default legend automatically whenever the argument groups
is used.
Alternatively, can use key=simpleKey(labels, ...).
simpleKey has simpler arguments and fewer options than
key. Default values will be used for the rest.
Or supply the arguments of simpleKey as a list to auto.key
Position of key usually specified by space which defaults to
"top".
Find an example that does what you want!
Examples in demo 4.9
R.M. Ripley (University of Oxford) R 2012/13 20 / 28
Graphics Lattice Graphics

Lattice plots: multiple plots

To put multiple plots on one screen, use arguments of


print.trellis.
Use newpage=TRUE on first.
Use more=TRUE on all but the last.
Specify the location using either position or split
position=c(xmin, ymin, xmax, ymax) specifies the
lower-left and upper-right corners, using a [0-1] coordinate
system in both directions
split=c(x, y, nx, ny) instructs to place plot in x, y
position of a rectangular grid of nx by ny plots. Origin is
top-left.
Examples in demo 4.10

R.M. Ripley (University of Oxford) R 2012/13 21 / 28


Graphics Lattice Graphics

Lattice plots: extended formula

Sometimes need to reshape data for graphs (and for


analysis!), to concatenate columns with an indicator of which
column the row came from.
There is a function reshape() to do this, but it is not very
user friendly.
Lattice has an extended formula interface, which can
sometimes avoid reshaping for plotting.
Use "+" in the formula
Argument outer controls whether the separate plots appear
in separate panels, or in one panel, distinguished as for
groups.
Examples in demo 4.11

R.M. Ripley (University of Oxford) R 2012/13 22 / 28


Graphics Lattice Graphics

Lattice plots: other arguments

Argument aspect can be used to specify the shape of the


plot.
aspect="fill" is same as pty="m" for base graphics.
aspect="xy" calculates the average angle of the lines on the
graph, and adjusts the shape to make this 45 degrees.
aspect="iso" constrains the scales to be the same on each
axis, so distances will be accurately represented. This can be
done in base graphics using asp=1 in call to plot.
xlab, ylab, xlim, ylim, main, sub
are available as in base graphics.

R.M. Ripley (University of Oxford) R 2012/13 23 / 28


Graphics Lattice Graphics

Updating Lattice Plots

Lattice plots can be updated using update: e.g. to alter the


strip labels and aspect ratio:
Depth <- equal.count(quakes$depth)
(tmp <- xyplot(lat ~ long | Depth,
data = quakes))
(tmp <- update(tmp,
strip = strip.custom(strip.names = TRUE,
strip.levels = TRUE), aspect = "iso"))

Single panels can be altered interactively after plotting e.g.


xyplot(time ~ dist, data=hills)
trellis.focus("panel", 1, 1)
panel.identify(hills$dist, hills$time,
row.names(hills))

R.M. Ripley (University of Oxford) R 2012/13 24 / 28


Graphics Lattice Graphics

Lattice plots: Example code


Four plots
xyplot(dist ~ speed,cars)
bwplot(count ~ spray,InsectSprays,
xlab="Type of Spray",
ylab="Number of Insects",
main="Insect Spray Data")
xyplot(mpg ~ disp, groups=cyl, data=mtcars,
xlab="Displacement (cu in.)",
ylab="Miles/(US)gallon",
main="Car Road Tests Data",
auto.key=TRUE)
xyplot(mpg ~ disp, groups=cyl, data=mtcars,
key=simpleKey(text=unique(
as.character(mtcars$cyl)), columns=3))

R.M. Ripley (University of Oxford) R 2012/13 25 / 28


Graphics Lattice Graphics

Other Packages for R Graphics

More facilities are provided by packages:


rgl 3d graphics
tourr 3d graphics. Package tourrGui provides a GUI.
(Note : Windows users: open an unbuffered device by
windows(buffered = FALSE))
iplots Interactive graphics (Not good on Macs, but try
pre-release Acinonyx).
vcd Categorical data
plotrix Various “tricks”
For examples, visit the R Graph Gallery

R.M. Ripley (University of Oxford) R 2012/13 26 / 28


Graphics Exercises

Exercises 4 Page 1

Use the dataset cars for exercise 1 and ChickWeight for


exercises 2-4.
1 Using base graphics, plot a graph of distance against speed.
Use red squares as the plotting character.
Alter the default axis labels to something more enlightening.
(e.g. units,...). Make the axis tick labels all horizontal.
Add a title
Add a dotted green line from the fit of a linear regression.
2 Plot a graph of weight against time given diet, with Chick as a
group. Join the points with lines.
Alter the strip labels to include the word ‘Diet’.
Alter the default axis labels to something more enlightening.
Add a title
Add a key using auto.key. On a standard graphics window, fit
the key into 10 columns, showing lines not points.

R.M. Ripley (University of Oxford) R 2012/13 27 / 28


Graphics Exercises

Exercises 4 Page 2

3 Plot a graph of weight against time given Chick.


Ensure that each row only shows chicks from one diet. (Hint:
look at the numbers of chicks on each diet.)
Alter the strip labels to include the diet number, with a ":"
between the two numbers.
4 Create a box-whisker plot of weight against diet given Time.
Strip labels should read Time: n
Identify the outliers in the panel for time=16, using
trellis.focus(),

R.M. Ripley (University of Oxford) R 2012/13 28 / 28

Potrebbero piacerti anche