The Art of R Programming

(WallPaper) #1
This has R draw a histogram and then callslocator()with the argu-
ment 1 , indicating we will click the mouse once. After the click, the function
returns a list with componentsxandy, thex- andy-coordinates of the point
where we clicked.
To use this information to place text, combine it withtext():

> text(locator(1),"nv=75")

Here,text()was expecting anx-coordinate and ay-coordinate, specify-
ing the point at which to draw the text “nv=75.” The return value oflocator()
supplied those coordinates.

12.1.10 Restoring a Plot.................................................


R has no “undo” command. However, if you suspect you may need to undo
your next step when building a graph, you can save it usingrecordPlot()and
then later restore it withreplayPlot().
Less formally but more conveniently, you can put all the commands
you’re using to build up a graph in a file and then usesource(), or cut and
paste with the mouse, to execute them. If you change one command, you
can redo the whole graph by sourcing or copying and pasting your file.
For our current graph, for instance, we could create file named
examplot.Rwith the following contents:

d1 = density(testscores$Exam1,from=0,to=100)
d2 = density(testscores$Exam2,from=0,to=100)
plot(d1,main="",xlab="")
lines(d2)
text(46.7,0.02,"Exam 1")
text(12.3,0.008,"Exam 2")

If we decide that the label for exam 1 was a bit too far to the right,
we can edit the file and then either do the copy-and-paste or execute the
following:

> source("examplot.R")

12.2 Customizing Graphs........................................................


You’ve seen how easy it is to build simple graphs in stages, starting with plot().
Now you can begin to enhance those graphs, using the many options R
provides.

12.2.1 Changing Character Sizes: The cex Option.......................


Thecex(forcharacter expand) function allows you to expand or shrink char-
acters within a graph, which can be very useful. You can use it as a named

272 Chapter 12

Free download pdf