-
Notifications
You must be signed in to change notification settings - Fork 0
/
7graphics.tex
2327 lines (2026 loc) · 82.4 KB
/
7graphics.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% !Rnw root = learnR.Rnw
\input{preamble}
\marginnote{The function \margtt{plot()} accepts a \margtt{data} argument,
while \margtt{lines()}, \margtt{points()} and \margtt{text()} do not.}
\noindent
\fbox{\parbox{\textwidth}{{\bf Base Graphics (mostly 2-D):}\\[4pt]
\begin{tabular}{ll}
\multicolumn{2}{l}{Base graphics implements a `traditional' style
of graphics}\\[0.15cm]
Functions & \code{plot()}, \code{points()}, \code{lines()},
\code{text()}, \\
& \code{mtext()}, \code{axis()},\code{identify()} etc. form\\
& a suite that plot points, lines, text, etc.\\[6pt]
\end{tabular}
}}
\vspace*{4pt}
\marginnote[27pt]{\pkg{lattice} and \pkg{ggplot2} are built on the low-level
graphics package \pkg{grid}.
Note also various special types of graph. For example
word clouds, as in the \pkg{wordcloud} package, list words
with size proportional to frequency.}
\noindent
\fbox{\parbox{\textwidth}{
{\bf Other Graphics}\\[4pt]
\begin{tabular}{ll}
\multicolumn{2}{l}{\quad (i) lattice (trellis) graphics, using the
\pkg{lattice} package,}\\
\multicolumn{2}{l}{\quad (ii) \pkg{ggplot2}, implementing Wilkinson's
\textit{Grammar of Graphics}}\\
\multicolumn{2}{l}{\quad (iii) For 3-D graphics (Section
\ref{sec:dynamicg}), note \pkg{rgl}, \pkg{misc3d} \&
\pkg{tkrplot}}\\
\multicolumn{2}{l}{\quad (iv) \textit{Motion Charts} (Section
\ref{sec:gvis}), show a scatterplot changing}\\
& with movement forward or backward in time.\\
\end{tabular}
}}
\vspace*{18pt}
Consider first base graphics. Relative to \pkg{lattice} and to {\em
ggplot2}, the more traditional style of base graphics is less
consistent and less structured. Each system however has its own
strengths and uses.
\begin{Schunk}
\begin{Sinput}
## DAAG has several datasets that will be required
library(DAAG, quietly=TRUE)
\end{Sinput}
\end{Schunk}
\section{Base Graphics}\label{sec:baseplots}
\begin{marginfigure}
To see a variety of base (or traditional) graphics plots, enter\\[-4pt]
\begin{Schunk}
\begin{Sinput}
demo(graphics)
\end{Sinput}
\end{Schunk}
\noindent Press Enter to see each new graph.
\end{marginfigure}
The function \code{plot()} is the most basic of several functions that
create an initial graph. Other functions can be used to add to an
existing graph. Note in particular \code{points()} \code{lines()} and
\code{text()}.
\subsection{\code{plot()} and allied base graphics functions}
The following are alternative ways to plot \code{y} against \code{x}
(obviously \code{x} and \code{y} must be the same length):
\begin{marginfigure}[-3pt]
Plot \margtt{height} vs \margtt{weight} --\\
\begin{Schunk}
\begin{Sinput}
## Older syntax:
with(women,
plot(height, weight))
\end{Sinput}
\end{Schunk}
\begin{Schunk}
\begin{Sinput}
## Graphics formula:
plot(weight ~ height,
data=women)
\end{Sinput}
\end{Schunk}
\end{marginfigure}
\begin{Schunk}
\begin{Sinput}
plot(y ~ x) # Use a formula to specify the graph
plot(x, y) # Horizontal ordinate, then vertical
\end{Sinput}
\end{Schunk}
The following use the argument \code{data} to supply the name of a
data frame whose column names appear in the graphics formula:
\begin{Schunk}
\begin{Sinput}
plot(distance ~ stretch, data=elasticband)
plot(ACT ~ year, data=austpop, type="l")
plot(ACT ~ year, data=austpop, type="b")
\end{Sinput}
\end{Schunk}
The \code{points()} function adds points, while \code{lines()} adds
lines\footnote{These functions differ only in the default
setting for the parameter \code{type}{\small .} Explicitly setting
\code{type = "p"} causes either function to plot points.} to a plot.
The \code{text()} function adds text at specified locations. The
\code{mtext()} function places text in one of the margins. The
\code{axis()} function gives fine control over axis ticks and labels.
Here is a further possibility
\begin{Schunk}
\begin{Sinput}
with(austpop, plot(spline(year, ACT), type="l"))
# Fit smooth curve through points
\end{Sinput}
\end{Schunk}
\subsection*{Adding text -- an example}\label{ss:addpoints}
Here is a simple example (Figure \ref{fig:primates}) that uses the
function \code{text()} to label the points on a plot. Data is from
the dataset \code{DAAG::primates}. The first two lines of
data are:
\begin{Schunk}
\begin{Sinput}
## Data (1st 2 lines)
head(primates, 2)
\end{Sinput}
\begin{Soutput}
Bodywt Brainwt
Potar monkey 10 115
Gorilla 207 406
\end{Soutput}
\end{Schunk}
\begin{marginfigure}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-brain-body-1} }
\end{Schunk}
\caption{Plot of brain weight against body weight, for selected
primates.
}\label{fig:primates}
\end{marginfigure}
Code for a simplified version of the plot is:
\begin{Schunk}
\begin{Sinput}
plot(Brainwt ~ Bodywt, xlim=c(0, 300),
ylim=c(0,1500), data=primates, fg="gray",
xlab="Body weight (kg)",
ylab="Brain weight (g)")
# Specify xlim to allow room for the labels
with(primates,
text(Brainwt ~ Bodywt, cex=0.8,
labels=rownames(primates), pos=4))
# pos: pos=1 (below), 2 (left), 3 (above)
\end{Sinput}
\end{Schunk}
\subsection*{Identification and Location on the Figure Region}
Draw the graph first, then call the required function.
\marginnote{Section \ref{ss:shortR} described how to
terminate the plot, if the limit \code{n} is not reached first.
For \code{locator()}, \code{n} is by default set to 500.}
\begin{itemizz}
\item[-] \code{identify()}, discussed in Subsection \ref{ss:shortR}, labels
points.
\item[-] \code{locator()} prints out the co-ordinates of
points. Position the cursor at the location for which coordinates are
required, and click the left mouse button.
\end{itemizz}
\subsection{Fine control -- Parameter settings}\label{ss:fine}
\begin{marginfigure}[24pt]
To store existing settings for later restoration, proceed thus:
\begin{Schunk}
\begin{Sinput}
oldpar <- par(cex=1.25)
# par(oldpar) to restore
\end{Sinput}
\end{Schunk}
\end{marginfigure}
In most (not all) instances, parameters can be set either using
\code{par()}, or in a call to a plotting function (\code{plot()},
\code{points()}, \ldots). Changes made using \code{par()} remain in
place until changed again, or until a new device is opened. If made
in a call to a plotting function, the change applies only to that
call.
Some of the more common settings are:\\[-3pt]
\begin{itemize}
\item[-] Plotting symbols: \verb+pch+ (choice of symbol); \verb+cex+
("character expansion")\sidenote{Thus \code{par(cex=1.2)}
increases plot symbol size 20\% above the default.}; \verb+col+
(color).
\item[-] Lines: \verb+lty+ (line type); \verb+lwd+ (line width); \verb+col+
(color).
\item[-] Axis limits: \verb!xlim!; \verb!ylim!.
\item[-] Closeness of fit to the axis limits: \code{xaxs},
\code{yaxs}.\sidenote{The default is \code{xaxs="r"}; $x$-axis limits are
extended by 4\% relative to data or \code{xlim} limits.} Specify
\code{xaxs="i"} for an exact fit to the data limits.
\item[-] Axis annotation and labels: \verb+cex.axis+ (for axis
annotation, independently of \verb+cex+);
\verb+cex.labels+ (for axis labels).
\item[-] Margins and positioning within
margin:\sidenote{Parameters such as \code{mar}, \code{mgp} and
\code{oma} specify distances in `lines' out from the relevant
boundary of the figure region. Lines are in units of \code{mex},
where by default \code{mex=1}.} \verb+mar+ (inner margins
clockwise from bottom, out of box default \code{mar=c(5.1, 4.1, 4.1,
2.1)}); \verb+oma+ (outer margins, use when there are multiple
plots on the one graphics page); positioning within margin:
\verb+mgp+ (margin line for the axis title, axis labels, and axis
line, default \code{mgp=c(3, 1, 0)}).
\item[-] Plot shape: \code{pty="s"} gives a square
plot.\sidenote{This must be set using \code{par()}}
(default is \code{pty="m"})
\item[-] Multiple graphs on the one graphics page: \marginnote{For a 1
by 2 layout of plots; specify \code{par(mfrow=c(1,2))}.
Subsection \ref{ss:sum-modobj} has an example.} \code{par(mfrow=c(m,n))}
gives an $m$
rows by $n$ columns layout.
\end{itemize}
Type \code{help(par)} to get a (very extensive) complete list. Figure
\ref{fig:pars} demonstrates some of the possibilities.
\subsection{Color and Opacity}
The function \code{colors()} gives access to 657 different color names,
some of them repeats of the same colour. The function \code{palette()}
can be used to show or set colors that will by default be used for base
graphics. Thus
\begin{itemizz}
\item[-] \code{palette()} lists the colors in the current palette;
\item[-] as an example, \code{palette(rainbow(6))} sets the current
palette to a 6-color rainbow palette;
\item[-] \code{palette("default")} resets back to the default.
\end{itemizz}
\marginnote[12pt]{See \code{help(palette)} for palettes in the base R
\pkg{grDevices} package.} Run the following code to show the
default palette, three sequential palettes from \pkg{grDevices}, a
color ramp palette given by the function \code{colorRampPalette()},
and two quantitative palettes from the \pkg{RColorBrewer} package.
\begin{fullwidth}
\begin{Schunk}
\begin{Sinput}
## Load to run code for Supplementary Figure 1
library(RColorBrewer) # Required for Set1 and Dark2 RColorBrewer palettes
\end{Sinput}
\end{Schunk}
\begin{Schunk}
\begin{Sinput}
colpal <- rev(list(
"Default palette" = palette()[1:8], cm.colors = cm.colors(12),
terrain.colors = terrain.colors(12), heat.colors = heat.colors(12),
blueRamp = colorRampPalette(c(blues9, "white"))(12),
"Brewer-Set1" = brewer.pal(8, "Set1"),
"Brewer-Dark2" = brewer.pal(8, "Dark2")))
palnam <- names(colpal)
plot(1, 1, xlim=c(0.5,12.5), ylim=c(0,length(palnam)+0.5), type="n",
axes=FALSE, xlab="", ylab="")
for(i in 1:length(palnam)){
len <- length(colpal[[i]])
points(1:len, rep(i,len), pch=15, col=colpal[[i]], cex=5.5)
legend(1, i+0.025, palnam[i], adj=0, box.col="white", bg="white",
x.intersp=0, y.intersp=0, yjust=0)
\end{Sinput}
\end{Schunk}
\end{fullwidth}
Each of these palettes, except the default, allows variation in the
number of colors, up to a maximum. The palettes available from {\em
RColorBrewer} include other qualitative palettes, sequential
palettes, and diverging (light in the middle; dark at the extremes)
palettes. To see the full range of \pkg{RColorBrewer} possibilities,
type: \marginnote{Stretch the graphics window vertically (pull on an
edge) so that rows do not overlap.}
\begin{Schunk}
\begin{Sinput}
display.brewer.all()
\end{Sinput}
\end{Schunk}
\noindent
\marginnote{While limited use of light colors is fine for
coloring regions on a map, light colors do not show up well
when coloring points on a graph.} Qualitative schemes that may be
suited for use in plots are "Set1" with yellow (the 6$^{th}$ color out
of nine) omitted, or "Dark2", or "Accent" with the 4$^{th}$ color
(out of 8) omitted. To extract these, do for example:
\begin{Schunk}
\begin{Sinput}
Set1 <- brewer.pal(8, "Set1")[-6]
## Check out the palette
plot(1:7, pch=16, cex=2, col=Set1)
\end{Sinput}
\end{Schunk}
\subsection*{Opacity, and graphs with many points}\label{ss:xpoint}
\begin{figure}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-alpha-ex-1} }
\end{Schunk}
\caption{In Panel A, points are plotted with the 100\% opacity, i.e.,
no transparency. In Panel B, \code{alpha=0.4}, i.e., 40\% opacity.
Panel C uses the function \code{smoothScatter()} to show a smoothed
color density representation of the data.\label{fig:alpha}}
\end{figure}
\marginnote[2pt]{An opacity of 0.4 has the effect that, for an
isolated point, 60\% of the white background shows through.}
\noindent
\begin{Schunk}
\begin{Sinput}
## Sample from the 15992 rows
dfsamp <- cps1[sample(nrow(cps1), 3000), ]
plot(re78 ~ re75, data=dfsamp, pch=20, cex=0.5,
col="black", las=0, fg="gray")
mtext(side=3, line=0.5, "A: 100% opacity", adj=0)
plot(re78 ~ re75, data=dfsamp, pch=20, cex=0.5, las=0,
col=adjustcolor("black", alpha=0.4), fg="gray")
mtext(side=3, line=0.5, "B: 40% opacity", adj=0)
blueRamp <- colorRampPalette(c("white", blues9))
with(dfsamp, smoothScatter(re75~re74, , fg="gray",
las=0, colramp=blueRamp))
mtext(side=3, line=0.5, "C: Color density plot",
adj=0)
\end{Sinput}
\end{Schunk}
With \code{alpha=0.4}, two overlapping points have a combined
opacity of 80\%, so that 20\% of the white background shows through.
Three or more overlapping points appear as completely black.
\marginnote[11pt]{The plots show a sample of 3000 of the
points. Plotting all the points gives an inconveniently large
graphics file, while not giving a more informative graph.} Compare
three plots shown in Figure \ref{fig:alpha}. Points overlap to such
an extent that Panel A, gives very limited information about the
density of points. Panel B, where the color opacity is 40\%, gives a
better indication of variation in the density of points. Panel C uses
the function \code{smoothScatter()} to provide a color density
representation of the scatterplot. This is a more nuanced
way to show the density of points.
\subsection{The shape of the graph sheet}
Aspect ratio, i.e., the ratio of $x$-distance to $y$-distance, has a
large say in what is visually obvious. Figures \ref{fig:aspect}A and
\ref{fig:aspect}B show the same data:
\begin{figure*}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-fig8_3e-1} }
\end{Schunk}
\caption[][-15pt]{Figures A and B show the same data, but with widely different
aspect ratios.\label{fig:aspect}}
\end{figure*}
\noindent
Features that are at an angle that is close to the horizontal or the
vertical are hard to detect visually. Patterns of change or other
features should, to be visually obvious, be offset by an angle of
at least 20$^\circ$ from both the horizontal and the vertical.
\noindent For each of Figures \ref{fig:aspect}A and \ref{fig:aspect}B
the code, after setting the dimensions of the figure page, is:
\begin{Schunk}
\begin{Sinput}
plot((1:30)*0.92, sin((1:30)*0.92),
xlab="", ylab="")
\end{Sinput}
\end{Schunk}
The dimensions of the graphics display can be specified when a
graphics window is opened. Once opened, the shape and size of a
screen device can be changed by clicking and dragging on one corner.
The R for Windows functions \code{win.graph()} or \code{x11()} that
set up the Windows screen take the parameters \code{width} (in
inches), \code{height} (in inches) and \code{pointsize} (in 1/72 of an
inch). The setting of \code{pointsize} (default =12) determines
character heights. It is the relative sizes that matter for screen
display or for incorporation into Word and similar programs.
\subsection{Multiple plots on the one page}\label{ss:xplots}
\marginnote[10pt]{For a layout in which columns are filled before
moving to a new row, use \margtt{mfcol} in place
of \margtt{mfrow}.}
The parameter \code{mfrow} can be used to configure the graphics
sheet so that subsequent plots appear row by row, one after the
other in a rectangular layout, on the one page. The following
presents four different transformations of data from the dataset
\code{MASS::Animals}), in a two by two layout:
\begin{Schunk}
\begin{Sinput}
## Supplementary figure 9.2
library(MASS)
oldpar <- par(pch=16, pty="s", mfrow=c(2,2))
with(Animals, { # bracket several R statements
plot(body, brain)
plot(sqrt(body), sqrt(brain))
plot(body^0.1, brain^0.1)
plot(log(body), log(brain))
}) # close both sets of brackets
par(oldpar) # Restore former settings
\end{Sinput}
\end{Schunk}
A more flexible alternative is to use the graphics parameter
\code{fig} to mark out the part of the graphics page on which the
next graph will appear. The following marks out, successively,
a plot region that occupies the upper 62\% of the plot region,
then the lower 38\%.
\marginnote[15pt]{\margtt{par(fig = c(0,1,0.38,1))} marks out a
plot region that is the total width, starts
38\% of the way up, and extends to the top.
\margtt{par(fig=c(0,1,0,0.38), new=TRUE)} marks out the lower
38\% of the page.}
\begin{Schunk}
\begin{Sinput}
par(fig = c(0, 1, 0.38, 1), mgp=c(3,0.5,0))
# xleft, xright, ybottom, ytop
## Panel A
par(fig = c(0, 1, 0, 0.38), new=TRUE)
## Plot graph B
par(fig = c(0, 1, 0, 1)) # Restore settings
\end{Sinput}
\end{Schunk}
The effect of \code{new=TRUE} is, somewhat
counter-intuitively, ``assume a new page is already open; do not open
a new page''.
\subsection{Plots that show the distribution of data values}
\marginnote{Density plots are much preferable, for most purposes, to
histograms. Both have limitations.} We discuss
histograms, density plots, boxplots and normal probability plots.
Normal probability plots are a specialized form of cumulative
density plot.
\subsection*{Histograms and density plots}
\begin{figure}[htbp]
\vspace*{-18pt}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-poss-hist-1} }
\end{Schunk}
\caption{The two panels show the same data, but with a different
choice of breakpoints.\label{fig:densitybreaks}}
\vspace*{-15pt}
\end{figure}
The shapes of histograms depend on the placement of the breaks, as
illustrated by Figure \ref{fig:densitybreaks}. The following code
plots the histograms and superimposes the density plots.
\marginnote[12pt]{The argument \code{freq=FALSE} gives a vertical
scale that is the number of points per unit interval, i.e., it is
the `density' estimate that is given by the upper bar of each
rectangle. This is needed for the superposition of a density curve
onto the histogram.}
\begin{Schunk}
\begin{Sinput}
ftotlen <- subset(possum, sex=="f")[, "totlngth"]
## Left panel: breaks at 72.5, 77.5,..
hist(ftotlen, breaks = 72.5 + (0:5)*5, freq=FALSE,
xlab="Total length", ylim=c(0,0.11),
main ="A: Breaks at 72.5, 77.5,...")
## Now superimpose a density curve, as in Fig. 7.3
lines(density(ftotlen))
##
## Panel B: breaks at 75, 80, ...
hist(ftotlen, breaks = 75 + (0:5)*5, freq=FALSE,
xlab="Total length", ylim=c(0,0.11),
main="B: Breaks at 75, 80, ...")
\end{Sinput}
\end{Schunk}
The height of each rectangle of a histogram is a crude density
estimate that changes in jumps, at breakpoints that are
inevitably chosen somewhat arbitrarily.
A smoothly changing density estimate, such as given by the
superimposed density curves in the panels of Figure
\ref{fig:densitybreaks}, makes better sense than an estimate that
changes in jumps.
\marginnote[12pt]{Neither histograms nor density plots are effective
for checking normality. For that, use a normal probability plot.}
Unless samples are very large, the shape of both histograms and
density plots will show large statistical variability. Density plots
are helpful for showing the mode, i.e., the density maximum.
The following gives a density plot, separately from the histograms that
are shown in \ref{fig:densitybreaks}.
\begin{Schunk}
\begin{Sinput}
## Supplementary figure 9.3
with(subset(possum, sex=="f"),
plot(density(totlngth), type="l"))
\end{Sinput}
\end{Schunk}
For use of density plots with data that have sharp lower and/or upper
cutoff limits, it may be necessary to specify the $x$-axis limit or
limits.\sidenote[][-18pt]{Thus, a failure time distribution will have a
sharp cutoff at zero, which may also be the mode.} Use the
parameters \code{from} and/or \code{to} for this purpose. This issue
most commonly arises with a lower cutoff at 0.
\subsection*{Boxplots}
Boxplots use a small number of characteristics of a distribution to
characterize it. Look up \code{help(boxplot)} for details.
It can be insightful to add a `rug' that shows the individual values,
by default along the horizontal axis (\code{side=1}).
Figure \ref{fig:boxrugs} is an example. Code for the plot is:
\begin{marginfigure}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-boxplot-1} }
\end{Schunk}
\vspace*{-12pt}
\caption{Distribution of lengths of female possums. The
vertical bars along the $x$-axis (together making up a 'rug')
show actual data values.\label{fig:boxrugs}}
\end{marginfigure}
\begin{Schunk}
\begin{Sinput}
## Code
with(subset(possum, sex=="f"),
{boxplot(totlngth, horizontal=TRUE)
rug(totlngth)} )
\end{Sinput}
\end{Schunk}
\subsection*{Normal probability plots}
\marginnote{A point pattern that is not consistent with random deviation
from a line indicates a non-normal distribution.}
The function \code{qqnorm(y)} gives a normal probability plot of the
values of \code{y}. In such a plot, data from a normal distribution
will be scattered about a line. To calibrate the eye to recognise
plots that indicate non-normal variation, it helps to compare the plot
for the data in hand with several normal probability plots that use
\code{rnorm()} to generate random values. Figure \ref{fig:np-plots}
is an example.
\begin{figure*}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-possum-qqn-1} }
\end{Schunk}
\caption[][7pt]{Normal probability plots. The top left panel
shows the 43 lengths
of female possums. Other panels are for independent normal
random samples of size 43.\label{fig:np-plots}}
\vspace*{-24pt}
\end{figure*}
\begin{Schunk}
\begin{Sinput}
## Q-Q plot for the data (top left panel)
ftotlen <- subset(possum, sex == "f")[, "totlngth"]
qqnorm(ftotlen, xlab="",
ylab=expression(bold("Data")))
## Code for a plot with random normal data
qqnorm(rnorm(43), xlab="", ylab="Simulated")
\end{Sinput}
\end{Schunk}
\noindent There is one unusually small value. Otherwise the points
for the female possum lengths are as close to a straight line as in
many of the plots for random normal data.
Plots of this type ought to be a standard part of statistical
practice.
\subsection{$^*$Plotting Text that Includes Technical Symbols}\label{sec:mathvec}
\marginnote[11pt]{Axis labels can be expressions, in \pkg{lattice} and
\pkg{ggplot2} as well as in base graphics. Tick labels can for
example be vectors of expressions.}
The functions \code{expression()} and {substitute()} can be used
to create mathematical expressions, for later evaluation or for
printing onto a graph. For example, \verb+expression(x^2)+ will
print, when supplied to \code{text()} or \code{mtext()} or another
such function (this includes \pkg{lattice} and \pkg{ggplot2} functions),
as $x^2$.
For purposes of adding text that includes mathematical and other
technical symbols, the notion of expression is generalized, to allow
`expressions' that it does not make sense to try to evaluate. For
example, \code{expression("Temperature (" * degree * "C)")} prints as:
$\mbox{Temperature (}^{\circ}\mbox{C)}$.
\marginnote[-22pt]{Items that are separated by an asterisk (\code{*})
are juxtaposed side by side. The initial text is followed by a
degree symbol, and then by the final text.}
The following indicate some of the possibilities:
\begin{itemizz}
\item[-] Letters such as \code{a}, \code{b}, \code{c}, \code{x},
\ldots are printed literally.
\item[-] \code{alpha} denotes the Greek letter $\alpha$, while
\code{Alpha} denotes the upper case symbol. Similarly for
other Greek letters.
\item[-] \code{hat(x)} denotes $\hat{\mbox{x}}$.
\item[-] \code{italic(x)}, \code{bold(x)}, \code{bolditalic(x)},
and \code{plain(x)} have the obvious meaning.
\item[-] \code{frac(a,b)} denotes $\frac{\mbox{a}}{\mbox{b}}$.
\end{itemizz}
Figure \ref{fig:area} demonstrates the use of an expression to
provide $y$-axis labeling. The code is:
\begin{marginfigure}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-plot-expr-1} }
\end{Schunk}
\caption{A mathematical expression is included as part of the
$y$-axis label.\label{fig:area}.}
\end{marginfigure}
\begin{Schunk}
\begin{Sinput}
yl <- expression("Area = " * pi * r^~2)
plot(1:5, pi*(1:5)^2, xlab="Radius (r)", ylab=yl)
\end{Sinput}
\end{Schunk}
\noindent The tilde (\verb+~+) in \verb+r^~2+ is used to insert a small space.
Use \code{substitute()} in place of \code{expression()} when
symbols in the expression are to be replaced by values that
will be provided at the time of forming the expression.
See \code{help(plotmath)} for further details of the conventions,
and of the symbols that are available. Type \code{demo(plotmath)}
to see a wide range of examples of what is possible.
\section{Lattice Graphics}
\marginnote[11pt]{The \pkg{lattice} package is included in all R binary
distributions that are available from a CRAN (Comprehensive R
Archive Network) mirror. It implements a `trellis' style of
graphics, as in the S-PLUS implementation of the S language. It is
built on the \pkg{grid} low-level graphics system, described in
Part II of Paul Murrell's \textit{R Graphics}}
\fbox{\parbox{\textwidth}{{\bf Lattice Graphics:}\\[4pt]
\begin{tabular}{ll}
\textbf{Lattice} & Lattice is a flavour of trellis graphics\\
& (the S-PLUS flavour was the original)\\[6pt]
Lattice & Lattice is more structured, automated and stylized.\\
vs base & For standard purposes, much is automatic.\\[6pt]
Lattice & Lattice syntax is consistent and tightly regulated\\
syntax & For lattice, graphics formulae are mandatory.
\end{tabular}
}}
\vspace*{9pt}
Lattice (trellis) graphics functions allow
\begin{marginfigure}
To see some of the possibilities that lattice graphics offers, enter
\begin{Schunk}
\begin{Sinput}
demo(lattice)
\end{Sinput}
\end{Schunk}
Functions that give styles of graph that are additional to
those described here include \margtt{contourplot()},
\margtt{levelplot()}, \margtt{cloud()}, \margtt{wireframe()},
\margtt{parallel()}, \margtt{qqmath()} and
\margtt{tmd()}.
\end{marginfigure}
the use of the layout on the page to reflect meaningful aspects
of data structure. Groups can
be readily distinguished within data, either using different colors
and/or symbols and/or line types within panels or using different
panels. Multiple columns of data can be plotted, either
distinguished within panels or using different panels.
Functions in the \pkg{latticeExtra} package
further extend what is available.
\marginnote[12pt]{These abilities, due to Felix Andrews, make it
possible to build up lattice graphics objects layer by layer.}
In the discussion that follows, there will be use of the layering
abilities provided by functions in \pkg{latticeExtra}. Note that
loading \pkg{latticeExtra} will at the same time load \pkg{lattice},
which \pkg{latticeExtra} has as a dependency.
\begin{Schunk}
\begin{Sinput}
library(latticeExtra, quietly=TRUE)
\end{Sinput}
\end{Schunk}
\subsection{Lattice graphics -- basic ideas}\label{ss:lat-gph}
\begin{marginfigure}
\begin{Schunk}
\centerline{\includegraphics[width=0.97\textwidth]{figs/07-cline-gph-1} }
\end{Schunk}
\caption{Use of lattice function \code{xyplot()} to give a graph.
\label{fig:lat-gph}}
\end{marginfigure}
Figure \ref{fig:lat-gph} was obtained using the lattice function
\code{xyplot()}. In this simple case, the syntax closely matches
that of the base graphics function \code{plot()}. Code is:
\begin{Schunk}
\begin{Sinput}
## On the command line: Create and print object
xyplot(Brainwt ~ Bodywt, data=primates)
\end{Sinput}
\end{Schunk}
\subsection*{Lattice graphics functions return graphics objects}
Note an important difference between lattice and base graphics.
Lattice graphics functions do not print graphs.\sidenote{This
applies also to \pkg{ggplot2}.} Instead they return
trellis graphics objects. The graph appears when the object is
printed (use \code{print()} or \code{plot()}). Sending the output
from a \pkg{lattice} graphics function to the command line invokes
\code{print()} and the graph is plotted, as was done for Figure
\ref{fig:lat-gph}.
A \code{Brainwt} versus \code{Bodywt} scatterplot for the
\code{primates} data, such as was given earlier, might alternatively
have been obtained using the function the function \code{xyplot()}
from the \pkg{lattice} package.
\begin{Schunk}
\begin{Sinput}
## Save the result as a trellis graphics object
# [For plot(), this is not possible.]
## Create trellis object
gph <- xyplot(Brainwt ~ Bodywt, data=primates)
## Print graph; a graphics device must now be open
print(gph)
\end{Sinput}
\end{Schunk}
The object \code{gph} need not be printed at this point. It can be
kept for printing at some later time. Or it can be updated, using the
function \code{update()}, and then printed, thus:
\begin{Schunk}
\begin{Sinput}
gph <- xyplot(Brainwt ~ Bodywt, data=primates)
gph2 <- update(gph, xlab="Body wt (kg)",
ylab="Brain wt (g)")
print(gph2) # Or it is enough to type 'gph2'
\end{Sinput}
\end{Schunk}
Inside a function\marginnote{The graph will however be
printed if \code{xyplot(...)} is the final statement
in a function that returns its result to the command line.}
or in a file that is sourced, \code{print()} must
ordinarily be used to give a graph, thus:
\begin{Schunk}
\begin{Sinput}
print(xyplot(ACT ~ year, data=austpop))
\end{Sinput}
\end{Schunk}
\subsection*{Addition of points, lines, text, \ldots}
For adding\sidenote{Do not try to use \margtt{points()} and other
such base graphics functions with lattice graphs.}
to a plot that has been created using a \pkg{lattice} function,
use \verb!panel.points()!, \verb!panel.text()!, and other such
functions, as will be described in Subsection \ref{ss:panel}.
Mechanisms for the control of a wide variety of stylistic
features are best discussed in the context of multi-panel
graphs, which we now consider.
\subsection{Panels of scatterplots}
Graphics functions in the \pkg{lattice} package, are designed to
allow row by column layouts of panels. Different panels are for
different subsets of the data. Additionally, points can be
distinguished, within panels, according to some further grouping
within the data.
The \code{DAAG::ais} dataset has data
\marginnote{See the \code{help(ais)} for details.}
from elite Australian athletes who trained at the Australian
Institute of Sport. These included height, weight, and other
morphometric measurements, as well as several types of blood
cell counts. A breakdown of the total of 202 athletes by sex
and sport gives:
\begin{fullwidth}
\begin{Schunk}
\begin{Sinput}
with(ais, table(sex,sport))
\end{Sinput}
\begin{Soutput}
sport
sex B_Ball Field Gym Netball Row Swim T_400m T_Sprnt Tennis W_Polo
f 13 7 4 23 22 9 11 4 7 0
m 12 12 0 0 15 13 18 11 4 17
\end{Soutput}
\end{Schunk}
\end{fullwidth}
\noindent
Figure \ref{fig:lattice-ais} demonstrates the use of \code{xyplot()},
for the rower and swimmer subset of the \code{ais} dataset. The two
panels distinguish the two sports, while different plotting symbols
(on a color device, different colors will be used) distinguish females
from males.
\begin{figure}[h]
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-rowSwim-1} }
\end{Schunk}
\caption{Height (\code{ht}) versus Weight (\code{wt}), for
rowers (\code{Row}) and swimmers (\code{Swim}).
Different plotting symbols are used to distinguish males from
females.}\label{fig:lattice-ais}
\end{figure}
\marginnote[11pt]{Use \margtt{auto.key=list(columns=2)} to generate a
simple key, with items side by side in two columns rather than
stacked in a single column as is the default
\margtt{columns=1}.}
\noindent
Suitable code is:
\begin{Schunk}
\begin{Sinput}
xyplot(ht ~ wt | sport, groups=sex, data=ais,
par.settings=simpleTheme(pch=c(4,1)),
scales=list(tck=0.5),
auto.key=list(space="right"),
subset=sport%in%c("Row","Swim"))
\end{Sinput}
\end{Schunk}
%$
In the graphics formula \verb!ht ~ wt | sport!,
\marginnote{Subsection \ref{ss:style}, which now follows,
explains the use of the argument \margtt{par.settings}, and its
call to \margtt{simpleTheme()}.}
the vertical bar indicates that what follows, in this case
\code{sport}, is a conditioning variable or factor. The
graphical information is broken down by levels of the factor
\code{sport}. The parameter \code{aspect} controls the ratio
of dimensions in the $y$ and $x$ directions.
\subsection{Setting stylistic features}\label{ss:style}
The function \code{simpleTheme()} creates a `theme', i.e., a list of
settings, that can be supplied via the argument \code{par.settings} in
the graphics function call. Use of the argument \code{par.settings}
to a lattice function makes the settings locally, for the specific
graphics object that results.
The \marginnote{Settings that are not available using
\code{simpleTheme()} can if required be added to the theme object
that \code{simpleTheme()} returns. See Subsection
\ref{ss:latticeParam} has details.}
function \code{simpleTheme()} accepts arguments \code{col},
\code{alpha}, \code{cex}, \code{pch}, \code{lty}, \code{lwd},
\code{font}, \code{fill}, \code{border}, plus \code{col.points},
\code{col.line}, \code{alpha.points} and \code{alpha.line}. These
allow separate control (of color and of opacity) for points and lines.
The function \code{trellis.device()} opens a new graphics device, with
settings that have in mind the use of \pkg{lattice} functions. The
function \code{trellis.par.set()} sets or changes stylistic features
for the current device. Both these functions accept an argument
\code{theme}.\sidenote{Simple variations on the default theme can be
created by a call to \code{simpleTheme()}.} Settings made by
\code{trellis.device()} or \code{trellis.par.set()} will be
over-written by any local settings that are stored as part of the
graphics object.
\subsection{Groups within data, and/or columns in parallel}\label{ss:grog}
Table \ref{tab:grog} shows selected rows from the dataset
\code{DAAG::grog}. Each of three liquor products (drinks) has
its own column. Rows are indexed by the factor \code{Country}.
% latex table generated in R 2.6.2 by xtable 1.5-2 package
% Mon Mar 31 10:08:43 2008
\begin{table}
\begin{center}
\caption{Apparent annual alcohol consumption values, obtained by dividing
estimates of total available alcohol by number of persons aged 15
or more. These are based on Australian Bureau of Statistics
and Statistics New Zealand figures.\label{tab:grog}}
\begin{tabular}{rrrrlr}
\hline
& Beer & Wine & Spirit & Country & Year \\
\hline
1 & 5.24 & 2.86 & 1.81 & Australia & 1998 \\
2 & 5.15 & 2.87 & 1.77 & Australia & 1999 \\
. . . .\\
9 & 4.57 & 3.11 & 2.15 & Australia & 2006 \\
10 & 4.50 & 2.59 & 1.77 & NewZealand & 1998 \\
11 & 4.28 & 2.65 & 1.64 & NewZealand & 1999 \\
. . . .\\
18 & 3.96 & 3.09 & 2.20 & NewZealand & 2006 \\
\hline
\end{tabular}
\end{center}
\end{table}
Figure \ref{fig:allgrog} is one of several possible displays that
might be used to summarize the information in Table \ref{tab:grog}.
It has been created by updating the following simplified code:
\noindent
\begin{Schunk}
\begin{Sinput}
## Simple version of plot
grogplot <- xyplot(
Beer+Spirit+Wine ~ Year | Country,
data=grog, outer=FALSE,
auto.key=list(columns=3))
\end{Sinput}
\end{Schunk}
\begin{figure}
\begin{Schunk}
\centerline{\includegraphics[width=\textwidth]{figs/07-grog-all-1} }
\end{Schunk}
\caption{Australian and New Zealand apparent per person annual
consumption (in liters) of the pure alcohol content of liquor products, for
1998 to 2006.\label{fig:allgrog}}
\end{figure}
\pagebreak
\noindent Observe that:
\begin{itemizz}
\item[-] Use of \code{Beer+Spirit+Wine} gives plots for each of
\code{Beer}, \code{Spirit} and \code{Wine}. The effect of
\margtt{outer=FALSE} is that these appear in the same panel.
\item[-] Conditioning by country (\code{$\mid$ Country}) gives separate
panels for separate countries.
\end{itemizz}
The following updates the object to give Figure \ref{fig:allgrog}:
\marginnote[12pt]{Notice the use of the function \code{simpleTheme()}
to set up a `theme' that was used to control point and line
settings.}
\begin{Schunk}
\begin{Sinput}
## Update trellis object, then print
ylab <- "Amount consumed (per person)"
parset <- simpleTheme(pch=c(1,3,4))
finalplot <- update(grogplot, ylim=c(0,5.5),
xlab="", ylab=ylab,
par.settings=parset)
print(finalplot)
\end{Sinput}
\end{Schunk}
Figure \ref{fig:allgrog} used different symbols, in the one panel, to
distinguish drinks, with different countries in different panels.
For separate panels for the three liquor products (different levels
of \code{Country} can then use the same panel), specify \code{outer=TRUE}:
\begin{Schunk}