-
Notifications
You must be signed in to change notification settings - Fork 3
/
p-062-customized-graphics.rmd
876 lines (604 loc) · 27.3 KB
/
p-062-customized-graphics.rmd
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
---
output:
html_document:
theme: readable
highlight: tango
toc: true
toc_depth: 1
number_sections: true
self_contained: false
css: textbook.css
---
```{r, echo=F }
knitr::opts_chunk$set( echo = TRUE, message=F, warning=F, fig.width=10)
```
```{r, echo=F}
library( dplyr )
library( Lahman )
library( pander )
```
# Customizing Plots
<div class="tip">
### Key Concepts
We can create almost any customized visualization using a small number of functions from the Core R graphics engine.
Creating a new canvas:
* plot.new()
* plot.window( xlim, ylim )
Adding data:
* points()
* lines()
* segments()
* ablines()
Annotating data:
* text()
Annotating the canvas:
* title()
* axis()
* box()
<br>
<br>
<br>
<br>
</div>
## Packages Used in This Chapter
We will use some data from the **Lahman** baseball data package for examples in this chapter.
The **People** data frame contains information about professional baseball players. We will focus on the relationship between height and weight of the players using the Body Mass Index (bmi) measure.
The data is interesting because it is easy to detect an abrubt and significant increase in baseball player size starting in the 1980's when the the abuse of steroids began.
![](http://2.bp.blogspot.com/_VM2gyxxMdEI/SucFZwYpWMI/AAAAAAAAABE/ToFDxoPFpbw/s400/jurystillout.JPG)
<center>
Mark McGuire before and after alleged steroid use.
</center>
```{r, echo=F}
# install.packages( "dplyr" )
# install.packages( "Lahman" )
library( dplyr ) # data wrangling
library( Lahman ) # baseball data
data( People )
```
```{r, echo=F}
People <- filter( People, birthYear > 1849 & birthYear < 1996 )
t1 <- tapply( People$height, People$birthYear, mean, na.rm=T )
t2 <- as.numeric( names( t1 ) )
plot( t2, t1, pch=19, type="b",
frame.plot=F,
xlab="Year of Birth",
ylab="Average Height (inches)",
main="Height of MLB Players Over Time" )
t1 <- tapply( People$weight, People$birthYear, mean, na.rm=T )
t2 <- as.numeric( names( t1 ) )
plot( t2, t1, pch=19, type="b",
frame.plot=F,
xlab="Year of Birth",
ylab="Average Weight (lbs)",
main="Weight of MLB Players Over Time" )
arrows( x0=1985, y0=180, y1=200, col="darkorange", lwd=3 )
text( x=1985, y=180, "Steroids!", pos=1, cex=1.5, col="darkorange" )
bmi <- (People$weight * 0.45359237) / (People$height / 39.370)^2
t1 <- tapply( bmi, People$birthYear, mean, na.rm=T )
t2 <- as.numeric( names( t1 ) )
plot( t2, t1, pch=19, type="b",
frame.plot=F,
xlab="Year of Birth",
ylab="Average BMI",
main="Body Mass Index of MLB Players Over Time" )
```
## Core Graphic Functions
```{r, eval=F}
points(
x=x, y=y, # plots points at the x,y positions
pch=19, # the type of point to plot
cex=2, # aspect ratio of point size
col="red", # color of points
bg="green" # fill color for open symbols
)
text(
x=x, y=y, # draws a line by connecting points
labels=some.text, # vector of labels to plot on the graph
pos=3, # position: 1=below, 2=left, 3=above, 4=right
cex=2, # aspect ratio of text size
col="red" # color of text
)
lines(
x=x, y=y, # draws a line by connecting points
lty="l", # type of lines, same as above
lwd=0.5, # line thickness
)
segments(
x0=x0, y0=y0, # starting points of the segments (usually a vector)
x1=x1, y1=y1, # end points of the segments (usually a vector)
... # other arguments from lines()
)
title(
main="Plot Title", # text for the plot title
xlab="x variable", # text for the x-axis label
ylab="y variable", # text for the y-axis label
line= -1 # move the title closer / further
)
axis(
side=1 # 1=below, 2=left, 3=above, 4=right
at=c(10,20,30), # position of tick marks
labels=c("S","M","L") # labels for tick marks
)
```
## Layering Approach
Graphs in R are created by layering elements on top of each other. The easiest way to understand this is to build a plot from piece by piece.
The following graph is comprised of six components:
* plot box
* points
* x-axis
* y-axis
* x-label
* y-label
Many other elements can be added to the plot, but you will see below the flexibility that is gained by mastering even the basic plotting functions.
### Load Player Data
The Lahman package is an example of a data package in R - one that does not include new functions or analytical tools. Rather, it contains player and team statistics stored as a collection of data frames to make it easy to share and deploy for any analytics involving player or team performance.
Datasets are loaded from R packages using the **data()** function.
```{r, eval=F}
# install.packages( "dplyr" )
# install.packages( "Lahman" )
library( dplyr ) # data wrangling
library( Lahman ) # baseball data
data( People )
```
```{r, echo=F}
preview.these <- c("nameFirst", "nameLast", "height", "weight", "birthYear")
head( People[ preview.these ] ) %>% pander()
```
Remove players that are missing height or weight measures:
```{r}
People <- select( People, height, weight, birthState )
People <- na.omit( People )
```
### Building the Canvas
Custom graphics in R allow you to create a blank canvas upon which you will add your data and your data narrative.
The canvas is the Cartesian coordinate system upon which you will place the data. You need to define the coordinate system before plotting any data using the **xlim=** and **ylim=** arguments.
The **plot.new()** function launches a new graphics window. The **plot.window()** function sets the coordinates.
```{r, fig.height=5, fig.width=5, eval=F}
plot.new()
plot.window( xlim=c( 1, 10 ), ylim=c( 1, 5 ) )
```
```{r, fig.height=3, fig.width=5, echo=F}
par( mar=c(3,3,3,3) )
plot.new()
plot.window( xlim=c( 1, 10 ), ylim=c( 1, 5 ) )
abline( h=1:5, col="gray" )
abline( v=1:10, col="gray" )
mtext( 1:5, at=1:5, side=4, col="gray", line=0.5, las=2 )
mtext( 1:10, at=1:10, side=3, col="gray", line=0.5, las=1 )
box("outer", col="navy")
```
<center>
_New canvas with the grid defined by **xlim** and **ylim** values._
</center>
Note that data can only be plotted on the canvas, but graphs also contain margins around the canvas used for titles, text, and axes.
```{r, echo=F, fig.width=10, fig.height=7.5}
# Generate data
x = 0:10;
y = 0:10;
# Plot the data
# - Specify the layout parameters before any plotting
# If you don't specify them before any plotting, the
# results will be inconsistent and misaligned.
#
# - oma stands for 'Outer Margin Area', or the total margin space that is outside
# of the standard plotting region (see graph)
#
# - The vector is ordered, the first value corresponding to the bottom. The entire
# array is c(bottom, left, top, right)
#
# - All of the alternatives are:
# - oma: Specify width of margins in number of lines
# - omi: Specify width of margins in inches
# - omd: Specify width of margins in 'device coordinates'
# - Device coordinates place (0,0) in the upper left and (1,1) in the
# lower right corner
# par(oma=c(3,3,3,3)) # all sides have 3 lines of space
# - The mar command represents the figure margins. The vector is in the same ordering of
# the oma commands.
#
# - The default size is c(5,4,4,2) + 0.1, (equivalent to c(5.1,4.1,4.1,2.1)).
#
# - The axes tick marks will go in the first line of the left and bottom with the axis
# label going in the second line.
#
# - The title will fit in the third line on the top of the graph.
#
# - All of the alternatives are:
# - mar: Specify the margins of the figure in number of lines
# - mai: Specify the margins of the figure in number of inches
par(mar=c(5,4,4,2) + 0.1)
# Plot
plot(x, y, type="n", xlab="", ylab="", yaxt="n",
col.axis="darkgreen", col.ticks="darkgreen" )
title( xlab="axis", family="mono", col.lab="darkgreen", cex.lab=2 )
box( col="darkorange" )
text( 5, 5, "Canvas", col="darkorange", cex=3 )
# Place text in the margins and label the margins, all in green
mtext("Margins", side=3, line=1, cex=2.5, col="darkgreen")
# mtext("par( mar=c(5,4,4,2) + 0.1 )", side=3, line=1, cex=1, col="darkgreen")
# mtext("Line 0", side=3, line=0, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 1", side=3, line=1, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 2", side=3, line=2, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 3", side=3, line=3, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 0", side=2, line=0, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 1", side=2, line=1, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 2", side=2, line=2, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 3", side=2, line=3, adj=1.0, cex=1, col="darkgreen")
box("figure", col="darkgreen")
# Label the outer margin area and color it blue
# Note the 'outer=TRUE' command moves us from the figure margins to the outer
# margins.
# mtext("Outer Margin Area", side=1, line=1.5, cex=2, col="navy", outer=TRUE)
# mtext("par( oma=c(3,3,3,3) )", side=1, line=2, cex=1, col="navy", outer=TRUE)
# mtext("Line 0", side=1, line=0, adj=0.0, cex=1, col="navy", outer=TRUE)
# mtext("Line 1", side=1, line=1, adj=0.0, cex=1, col="navy", outer=TRUE)
# mtext("Line 2", side=1, line=2, adj=0.0, cex=1, col="navy", outer=TRUE)
# box("outer", col="navy")
# mtext( "This is mtext", side=2, outer=T, line=1, col="navy" )
```
We need to pick a grid that suits our data. Since we will examine the relationship between **height** and **weight** we will use the min and max values of these variables to create the bounding box for our canvas.
```{r}
# find max and min values for each variable
xmin <- min( People$height )
xmax <- max( People$height )
ymin <- min( People$weight )
ymax <- max( People$weight )
# empty plot
plot.new()
plot.window( xlim=c(xmin,xmax), ylim=c(ymin,ymax) )
box( col="black" )
box( "outer", col="gray" )
text( 64, 200, "(Empty Canvas)", cex=2 )
```
### Add Points
We can now add some data to the canvas:
```{r}
plot.new()
plot.window( xlim=c(xmin,xmax), ylim=c(ymin,ymax) )
box( col="black" )
box( "outer", col="gray" )
points( People$height, People$weight, pch=19 )
```
### Add axes
```{r}
# add an x-axis and y-axis
plot.new()
plot.window( xlim=c(xmin,xmax), ylim=c(ymin,ymax) )
box( "outer", col="gray" )
points( People$height, People$weight, pch=19 )
axis( side=1 )
axis( side=2, las=1 ) # las turns the y-axis tick mark numbers
```
### Add Axis Labels
```{r}
# add axis labels
plot.new()
plot.window( xlim=c(xmin,xmax), ylim=c(ymin,ymax) )
points( People$height, People$weight, pch=19 )
axis( side=1 )
axis( side=2, las=1 )
title( xlab="Height (inches)", ylab="Weight (lbs)" )
title( main="Relationship Between Height and Weight of MLB Players" )
```
### Improving Aesthetics
Now let's see if we can improve the look and feel of the graph to make the narrative pop.
This is pretty dense data, so let's see if we can use some color transparency to get a sense of typical players versus outliers.
We can adjust the xlim and ylim arguments so we don't show the empty bottom left quadrant, and let's use the **gray()** color function to add some transparency to the over-plotted data points.
The first argument of the **gray()** function is a value between 0 and 1 specifying how dark you want the gray (0 being white, 1 being black), and the second argument is another value between 0 and 1 specifying the transparency of the points (0 being invisible and 1 being no transparency).
We can also jitter them a bit (a tiny amount of random error to each data point) so they are not all plotted on top of each other since height and weight only take integer values.
```{r, fig.height=6}
# rnorm() adds random noise to a data point
height.jitter <- People$height + rnorm( nrow(People) )
weight.jitter <- People$weight + rnorm( nrow(People) )
plot.new()
plot.window( xlim=c(62,xmax), ylim=c(110,ymax) )
points( height.jitter, weight.jitter,
pch=19, cex=1.5, col=gray(0.5,0.1) )
axis( side=1 )
axis( side=2 )
title( xlab="Height (inches)", ylab="Weight (lbs)",
main="Relationship Between Height and Weight of MLB Players" )
```
### Highlighting Groups
This is helpful, but maybe we want to highlight a group within the data.
Perhaps we have a theory that corn-fed players that grew up in Iowa are taller and weigh more.
```{r, fig.height=6}
plot.new()
plot.window( xlim=c(60,xmax), ylim=c(110,ymax) )
axis( side=1 )
axis( side=2 )
title( xlab="Height (inches)", ylab="Weight (lbs)",
main="Relationship Between Height and Weight of MLB Players" )
points( height.jitter, weight.jitter,
pch=19, cex=2, col=gray(0.5,0.02) )
# highlight players from Iowa
these.iowa <- People$birthState == "IA"
# use our selection vector to subset the data used in overplotting
points( height.jitter[ these.iowa ],
weight.jitter[ these.iowa ],
pch=19, cex=0.5, col="firebrick3" )
points( 63, 250, pch=19, col="firebrick" )
text( 63, 250, "Players form Iowa",
pos=4, cex=1.5, col="darkgray" )
```
Let's add another layer with only the data that falls within the 25th to 75th percentiles of BMI, what we might consider "averaged" sized players relative to their height.
```{r, fig.height=6}
plot.new()
plot.window( xlim=c(60,xmax), ylim=c(110,ymax) )
axis( side=1 )
axis( side=2 )
title( xlab="Height (inches)", ylab="Weight (lbs)",
main="Relationship Between Height and Weight of MLB Players" )
points( height.jitter, weight.jitter,
pch=19, cex=2, col=gray(0.5,0.02) )
# highlight average-sized players
bmi <- (People$weight * 0.45359237) / (People$height / 39.370)^2
bmi.25th <- quantile( bmi, 0.25, na.rm=T )
bmi.75th <- quantile( bmi, 0.75, na.rm=T )
# group definition: bmi > bmi.25th & bmi < bmi.75th
points( height.jitter[ bmi > bmi.25th & bmi < bmi.75th ],
weight.jitter[ bmi > bmi.25th & bmi < bmi.75th ],
pch=19, cex=0.1, col="firebrick3" )
```
## Highlighting Cases
Let's look back at the original plot. Do you see anything strange?
```{r, echo=F}
# add axis labels
plot.new()
plot.window( xlim=c(xmin,xmax), ylim=c(ymin,ymax) )
points( People$height, People$weight, pch=19 )
axis( side=1 )
axis( side=2 )
title( xlab="Height (inches)", ylab="Weight (lbs)" )
title( main="Relationship Between Height and Weight of MLB Players" )
points( People$height[which.min(People$height)],
People$weight[which.min(People$weight)],
col="firebrick", cex=2, lwd=2 )
text( People$height[which.min(People$height)]+1,
People$weight[which.min(People$weight)]+20,
"Is This an Error?", col="firebrick", pos=4, cex=1.5 )
```
The smallest data point in the dataset seems to represent a baseball player that is 40 inches tall and weighs 80 pounds. That *must* be some sort of data entry error, right?
```{r}
data( People)
People[ which.min(People$height) , c(14,15,17:20,2) ] %>% pander()
```
It turns out that [Eddie Gaedel](https://www.theversed.com/10266/the-tragic-story-of-eddie-gaedel-the-shortest-player-in-mlb-history/#.i0Qgkojft1), at 3 foot 7 inches, was the shortest man to ever play on a professional team. He was hired by the owner of the St. Louis Browns as a publicity stunt. He was so short that his strike zone, which goes form the knee to mid-chest, was too small for most pitchers. Crowds would cheer as he would quickly accumulate walks.
```{r, echo=F, out.width='70%' }
knitr::include_graphics( "figures/eddie_gaedel.png" )
```
Perhaps it would be useful to annotate some of the outliers on our graph. To do this, we can use the text() function.
```{r, eval=F}
text(
x=x, y=y, # draws a line by connecting points
labels=some.text, # vector of labels to plot on the graph
pos=3, # position: 1=below, 2=left, 3=above, 4=right
cex=2, # aspect ratio of text size
col="red" # color of text
)
```
Let's start by circling some data points. We do this by plotting a slightly larger point around the originals for the tallest, shortest, and heaviest players.
```{r}
plot.new()
plot.window( xlim=c(0,1), ylim=c(0,1) )
points( 0.5, 0.5, pch=19, col="gray", cex=3 )
points( 0.5, 0.5, pch=1, cex=5, col="firebrick" )
title( main="Large Hollow Point Plotted \nOver Solid Point" )
```
```{r, echo=F}
data( People )
```
```{r}
this.shortest <- which.min(People$height)
this.tallest <- which.max(People$height)
this.heaviest <- which.max(People$weight)
People[ c(this.shortest,this.tallest,this.heaviest), c(14,15,17:20,2) ] %>% pander()
```
Let's highlight the three outliers in our dataset.
```{r}
plot( People$height, People$weight,
pch=19, col="gray",
frame.plot=FALSE,
xlab="Height (inches)",
ylab="Weight (lbs)",
main="Relationship Between Height and Weight of MLB Players" )
points( People$height[ this.shortest ],
People$weight[ this.shortest ],
col="firebrick", cex=2, lwd=2 )
points( People$height[ this.tallest ],
People$weight[ this.tallest ],
col="firebrick", cex=2, lwd=2 )
points( People$height[ this.heaviest ],
People$weight[ this.heaviest],
col="firebrick", cex=2, lwd=2 )
text( People$height[ this.shortest ],
People$weight[ this.shortest ],
"Some Text Here", col="firebrick", pos=3 )
```
We add text to the graph through the x,y coordinate for the text, the text itself, and the **pos=** argument is used to specify where the text should go.
* pos=1: below
* pos=2: left
* pos=3: top
* pos=4: right
* no pos: on the point
You can see that we have a problem above. Our text above Eddie Gaedel is lopped off because it wanders outside of the plot window. We can add additional real estate by expanding plot window with the **xlim=** and **ylim=** arguments.
You can add a line break to a string by including the carriage return symbol '\n' in the string.
```{r, fig.height=5}
data( People)
plot( People$height, People$weight,
pch=19, col="gray", cex=0.8,
xlim=c(30,100), ylim=c(50,450),
frame.plot=FALSE,
xlab="Height (inches)",
ylab="Weight (lbs)",
main="Relationship Between Height and Weight of MLB Players" )
d.small <- People[ c(this.shortest,this.tallest,this.heaviest), c(14,15,17:20,2) ]
points( d.small$height,
d.small$weight,
col="firebrick", cex=2, lwd=2 )
text( People$height[ this.shortest ],
People$weight[ this.shortest ],
"Eddie Gaedel \nHeight: 43 Inches \nWeight: 65 Lbs",
col="firebrick", cex=0.8, pos=3, offset=1 )
text( People$height[ this.tallest ],
People$weight[ this.tallest ],
"Jon Rauch \nHeight: 83 Inches \nWeight: 290 Lbs",
col="firebrick", cex=0.8, pos=4, offset=1 )
text( People$height[ this.heaviest ],
People$weight[ this.heaviest ],
"Walter Young \nHeight: 77 Inches \nWeight: 320 Lbs",
col="firebrick", cex=0.8, pos=3, offset=1 )
```
## Using Text as Plot Points
As you can see, the **text()** function can be used to add narrative to a graphic. It can also be used in place of plotting points.
Let's think about testing the hypothesis that players have gotten larger over time. When we look at the basic relationship between height and weight we see the distribution of player sizes, but this plot has no information about the time-periods in which they played so we can't tell if they are growing larger over time. What if we replace the plotting points with birth years?
```{r}
plot.new()
plot.window( xlim=c(60,xmax), ylim=c(110,ymax) )
text( x=People$height,
y=People$weight,
labels=People$birthYear )
```
This is too dense to be meaningful. Maybe we can try to make the text smaller?
```{r}
plot.new()
plot.window( xlim=c(60,xmax), ylim=c(110,ymax) )
text( x=People$height,
y=People$weight,
labels=People$birthYear, cex=0.5 )
```
Still not very insightful. We have over 19,000 players in the database, which appears to be too many for this graphic. Let's thin the data out by taking a random sample of the full dataset.
```{r, fig.height=6}
par( mar=c(0,0,0,0) )
m.sample <- sample_n( People, 100 )
plot.new()
plot.window( xlim=c(65,78), ylim=c(130,280) )
text( x=m.sample$height,
y=m.sample$weight,
labels=m.sample$birthYear, cex=0.8 )
axis( side=1, line=-2 )
axis( side=2, line=-2 )
```
This is a big improvement. We can eyeball the data and start to pull out some trends. The people born in the 1800's tend to be near the bottom of each pile of years, for example.
Perhaps we can improve our visual hypothesis testing if we add some color coding. Let's identify all of the individuals born since 1980 and color their birth years red to highlight the youngest cohort in the data. If people have gotten larger over time, we would expect this group to cluster near the top of the distribution.
```{r, eval=F}
red.gray <- ifelse( m.sample$birthYear >= 1980, "firebrick", "gray" )
text( x=m.sample$height,
y=m.sample$weight,
labels=m.sample$birthYear,
col=red.gray )
```
```{r, echo=F, fig.height=6}
red.gray <- ifelse( m.sample$birthYear >= 1980, "firebrick", "gray" )
par( mar=c(0,0,0,0) ) # minimize margins
plot.new()
plot.window( xlim=c(65,78), ylim=c(130,280) )
text( x=m.sample$height,
y=m.sample$weight,
labels=m.sample$birthYear,
col=red.gray, cex=1 )
axis( side=1, line=-2 )
axis( side=2, line=-2 )
title( main="Player Height and Weight by Birth Year", line=-2 )
```
And we in fact see the pattern emerge. The youngest cohort, highlighted in red, seems to cluster near the top right, which suggests they have grown both taller and heavier over time.
This hypothesis can be test more rigorously in other ways, but the demonstration at least gives an idea about how we might explore the data efficiently using flexible R graphing functions.
```{r, eval=F, echo=F}
data( Teams )
plot( Teams$H, Teams$W, pch=19, col="gray" )
lines( lowess( Teams$H, Teams$W ), col="red", lwd=4 )
# identify( Teams$H, Teams$W, Teams$name )
plot( Teams$ERA, Teams$W, pch=19, col="gray" )
lines( lowess( Teams$ERA, Teams$W ), col="red", lwd=4 )
era.20.bins <- cut( rank( Teams$ERA), breaks=20 )
t2 <- tapply( Teams$W, era.20.bins, mean, na.rm=T )
t3 <- tapply( Teams$ERA, era.20.bins, mean, na.rm=T )
points( t3, t2, pch=19, col="red", cex=2 )
names( Teams )
```
# Additional Parameters
The small number of functions introduced here in these chapters on data visualization can be used to make highly-customizable graphics that help you discover important patterns in the data and share the story with others.
We are only scratching the surface on the options available within plotting functions. To see the default list of parameter settings in the R **plot()** function, type:
```{r, eval=F}
par()
help( par )
```
These chapters show how core R graphics can be used to create highly-customized graphics. You can see that you have fine-tuned access to all aspects of the figures you create. You don't have to become familiar with all of the options to develop solid visualization skills. Rather, you will likely focus on a few specific functions. A little time invested in learning the arguments for **plot()**, **points()**, **lines()**, **text()**, **title()**, and **axis()** goes a long way.
## Margins
It is sometimes helpful to include narrative in the margins instead of on actual graph. In these cases you need to expand your margins and use the **title()**, **axis()** and **mtext()** functions. The margins themselves are controlled by the inner margin **mar=c** argument and outer margin **oma=c** arguments in the graphical parameters function **par()**, which is called prior to your plot function to change how a new plot will be laid out.
Similar to other parameters, the four argument values refer to the bottom, left, top, and right regions on the graph.
```{r, eval=F}
par( mar=c(5,4,4,2), oma=c(3,3,3,3) )
plot( ... )
```
```{r, echo=F, fig.width=10, fig.height=6}
# Generate data
x = 0:10;
y = 0:10;
# Plot the data
# - Specify the layout parameters before any plotting
# If you don't specify them before any plotting, the
# results will be inconsistent and misaligned.
#
# - oma stands for 'Outer Margin Area', or the total margin space that is outside
# of the standard plotting region (see graph)
#
# - The vector is ordered, the first value corresponding to the bottom. The entire
# array is c(bottom, left, top, right)
#
# - All of the alternatives are:
# - oma: Specify width of margins in number of lines
# - omi: Specify width of margins in inches
# - omd: Specify width of margins in 'device coordinates'
# - Device coordinates place (0,0) in the upper left and (1,1) in the
# lower right corner
par( oma=c(4,3,4,3) ) # all sides have 3 lines of space
# - The mar command represents the figure margins. The vector is in the same ordering of
# the oma commands.
#
# - The default size is c(5,4,4,2) + 0.1, (equivalent to c(5.1,4.1,4.1,2.1)).
#
# - The axes tick marks will go in the first line of the left and bottom with the axis
# label going in the second line.
#
# - The title will fit in the third line on the top of the graph.
#
# - All of the alternatives are:
# - mar: Specify the margins of the figure in number of lines
# - mai: Specify the margins of the figure in number of inches
par( mar=c(5,4,4,2) + 0.1 )
# Plot
plot(x, y, type="n", xlab="", ylab="", yaxt="n", xaxt="n" ) # type="n" hides the points
axis( side=1, col="darkorange", col.axis="orange" )
title( xlab="axis( side=1 )", family="mono", col.lab="darkorange", line=2 )
title( xlab="title( xlab='my label' )", family="mono", col.lab="darkorange", line=3 )
box( col="darkorange" )
text( 5, 5, "Canvas", col="darkgray", cex=2 )
# Place text in the margins and label the margins, all in green
mtext("Margins", side=3, line=2, cex=2, col="darkgreen")
mtext("par( mar = c(5,4,4,2) + 0.1 )",
side=3, line=0.5, cex=0.8, col="darkgreen", family="mono" )
mtext("Line 0", side=3, line=0, adj=1.0, cex=1, col="darkgreen")
mtext("Line 1", side=3, line=1, adj=1.0, cex=1, col="darkgreen")
mtext("Line 2", side=3, line=2, adj=1.0, cex=1, col="darkgreen")
mtext("Line 3", side=3, line=3, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 0", side=2, line=0, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 1", side=2, line=1, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 2", side=2, line=2, adj=1.0, cex=1, col="darkgreen")
# mtext("Line 3", side=2, line=3, adj=1.0, cex=1, col="darkgreen")
box("figure", col="darkgreen")
# Label the outer margin area and color it blue
# Note the 'outer=TRUE' command moves us from the figure margins to the outer
# margins.
mtext("Outer Margin Area", side=1, line=1, cex=2, col="navy", outer=TRUE)
mtext("par( oma = c(4,3,4,3) )",
side=1, line=2.5, cex=1, col="navy", outer=TRUE, family="mono" )
mtext("Line 0", side=1, line=0, adj=1, cex=1, col="navy", outer=TRUE)
mtext("Line 1", side=1, line=1, adj=1, cex=1, col="navy", outer=TRUE)
mtext("Line 2", side=1, line=2, adj=1, cex=1, col="navy", outer=TRUE)
mtext("Line 3", side=1, line=3, adj=1, cex=1, col="navy", outer=TRUE)
box("outer", col="navy")
mtext( "This is mtext", side=3, outer=T, line=2, cex=1.5, col="navy" )
mtext( 'mtext( "This is mtext", side=2, outer=T, line=1 )',
side=3, outer=T, line=1, cex=1, col="navy", family="mono" )
```