-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10-graphics2.Rmd
More file actions
1131 lines (852 loc) · 52.2 KB
/
10-graphics2.Rmd
File metadata and controls
1131 lines (852 loc) · 52.2 KB
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
# R graphics: Round II {#graphics2}
R offers several different types of graphics: *<span style="color:#FF9966">grid</span>* graphics is contained in package `grid`; the package `lattice` contains *<span style="color:#FF9966">trellis</span>* graphics; the package `ggplot2` introduces *<span style="color:#FF9966">ggplot</span>* graphics to be implemented by the function `ggplot()`. In this chapter, further aspects of what is known as *traditional R graphics* are studied before moving on to ggplot graphics.
## Graphics parameters
(a) Study the help file of `par()`. Execute `par()` to obtain a list of all the current values of the graphical parameters.
(b) How is `par()` used to obtain the current setting of a specific graphics parameter e.g. the parameter `fin`?
```{r, fin}
par("fin")
```
(c) How is `par()` used to change a graphics parameter e.g. `mfrow`?
(d) How do you reset the changed values to their original values? Note the `no.readonly` argument of `par()`. *Hint*: Study the following instructions and there effects carefully:
```{r, par_col_example}
par('col')
```
<div style="margin-left: 25px; margin-right: 20px;">
The current colour for graphics is "black".
</div>
```{r, col_blue_example}
temp <- par(col = "blue")
```
<div style="margin-left: 25px; margin-right: 20px;">
Change colour for graphics to "blue".
</div>
```{r, par_value}
temp
```
<div style="margin-left: 25px; margin-right: 20px;">
Temp is a list of parameter(s) **BEFORE** change was made.
</div>
```{r, par_col_blue}
par('col')
```
<div style="margin-left: 25px; margin-right: 20px;">
Shows that the colour for graphics was indeed changed to "blue".
</div>
(e) It is sometimes useful to use `par (ask = TRUE)` to instruct R to ask you whether an existing graph should be replaced by a new one.
::: {style="color: #80CC99;"}
(f) Draw a histogram of variable Ozone in the data set `airquality` where each class interval is randomly represented by a different colour. What happened to the `NA` values?
:::
## Layout of graphics
(a) Review Figure \@ref(fig:figRegion). Note the parameters that are discussed there.
(b) Multiple figures on one page: How do the graphical parameters `mfg` and `mfrow` or `mfcol` differ? What are represented in the R data sets `ldeaths`, `mdeaths` and `fdeaths`? Use `mfg` and `mfrow` to obtain Figure \@ref(fig:fmdeaths). *Hint*: The graphics parameters `mfg` and `mfrow` are used together.
```{r, fmdeaths, echo=FALSE, fig.cap="Plots of the fdeaths and mdeaths data sets.", out.width="100%"}
par (mfrow = c(3,2), mfg = c(1,1))
qqnorm (fdeaths, main = "Normal Plot for Female deaths")
par (mfg = c(1,2))
hist (fdeaths, main = "Histogram for Female deaths")
par (mfrow = c(3,1), mfg = c(2,1))
ts.plot (fdeaths, ylim = c(250, 3000), main = "TS plot for Female and Male deaths")
lines (mdeaths, lty = 2, col = "red")
par (mfrow = c(3,2), mfg = c(3,1))
qqnorm (mdeaths, main = "Normal Plot for Male deaths")
par (mfg = c(3,2))
hist (mdeaths, main = "Histogram for Male deaths")
```
```{r, 10_1_b_1, eval = FALSE}
par (mfrow = c(3, 2), mfg = c(1, 1))
```
<div style="margin-left: 25px; margin-right: 20px;">
The `mfrow` setting reserves three rows and two columns for graphics to be filled row-wise. The `mfg` setting specifies that the next graph will be placed in the position defined by row one column one. Once this graph has been constructed the instruction
</div>
```{r, 10_1_b_2, eval = FALSE}
par (mfg = c(1, 2))
```
<div style="margin-left: 25px; margin-right: 20px;">
will result in the next graph to appear in the position defined by row one and column two. Next we need the instruction
</div>
```{r, 10_1_b_3, eval = FALSE}
par (mfrow = c(3, 1), mfg = c(2, 1))
```
<div style="margin-left: 25px; margin-right: 20px;">
requesting a graph window having three rows and one column with the next graph to appear at position row two (only one column in row two).
</div>
(c) Note how the meaning of the margins changes when more than one figure is drawn on a page to make provision for an *<span style="color:#FF9966">outer margin</span>* surrounding all figures in addition to the *<span style="color:#FF9966">margin</span>* surrounding each separate figure.
(d) Study how the functions `split.screen()`, `screen()` and `close.screen()` work as explained in the help facility.
(e) Study the usage of the function `layout()` in detail for more complicated arrangements of the graph window. An example of its usage is deferred until later in the chapter.
## Low-level plotting commands
* The functions in Table \@ref(tab:lowlevelPlotFuncs) are used to edit existing graphs.
* Study these functions carefully.
* Study how the right mouse button is used with R graphs.
* Most plotting tasks require some combination of high-level and low-level plotting commands.
Table: (\#tab:lowlevelPlotFuncs) Low-level plotting functions.
| *<span style="color:#F7CE21">Function</span>* | *<span style="color:#F7CE21">Description</span>* |
| ------ | --------------- |
| `abline()` | Add regression lines to a plot; Also for adding a vertical and horizontal lines to a plot |
| `arrows()` | Draw arrow on plot |
| `axis()` | Add custom axis to plot |
| `box()` | Draw box around plot |
| `chull()` | Compute a convex hull |
| `jitter()` | Add a small amount of noise |
| `legend()` | Add a legend to a plot |
| `lines()` | Add lines to a plot |
| `mtext()` | Write text in margins |
| `points()` | Add points to a plot |
| `polygon()` | Draw and shade polygons |
| `rug()` | Add data-based marks to an axis |
| `segments()` | Draw disconnected line segments |
| `symbols()` | Draw symbols on a plot |
| `text()` | Add text to a plot |
| `title()` | Add titles or axis labels to a plot |
## Using the plotting commands
### Multiple lines or groups of points on the same graph {#matplot}
Study how the function `matplot()` works. Note the functions `matlines()` and `matpoints()`. Study and execute the following example:
```{r, matplotExample, fig.cap="Three methods of performing sort.", out.width="100%"}
my.func <- function ()
{ times <- matrix(0,100,3)
for(i in 1:100)
{ n <- i * 10000
s1 <- 1:n
s2 <- sample(n)
s3 <- rnorm(n)
times[i,1] <- system.time(sort(s1))[1]
times[i,2] <- system.time(sort(s2))[1]
times[i,3] <- system.time(sort(s3))[1]
}
matplot(x = (1:100)*10000, y= times, type = "l", lty = 1:3,
col = c("black", "green", "red"), xlab = "Length",
ylab = "Time in seconds", main = "Time for sorting")
}
my.func()
```
### Multiple lines or groups of points on the same graph but the lines (points) are not all the same length (number) {#multipleLines}
What technique must be followed? First study the `Cars93` data set in package `MASS`; then study and execute the code below. Experiment with different values of `spar`.
```{r, diffLengths, fig.cap="Plotting multiple lines of different lenghts", out.width="100%"}
my.func <- function (spar = 0.9)
{ require (MASS) # What is the effect of require()?
oldstate <- par (no.readonly = TRUE) # Describe object 'oldstate'
on.exit (par (oldstate)) # Of what use is on.exit()?
par (mfrow = c(1,2))
cargrp <- Cars93[ , "Type"]
price <- Cars93[ , "Price"]
mpg.city <- Cars93[ , "MPG.city"]
mpg.highway <- Cars93[ , "MPG.highway"]
plot(price, mpg.city, type = "n", ylim = c(0, max(mpg.city)),
main = "Fuel Con. vs Price for City", xlab = "Price",
ylab = "Miles per Gallon in City")
jj <- 0
for(i in levels(cargrp))
{ jj <- jj+1
lines (smooth.spline (price[cargrp==i], mpg.city[cargrp==i], spar=spar),
lty = jj, col = jj, lwd=2)
}
plot(price, mpg.highway, type = "n", ylim = c(0, max(mpg.highway)),
main = "Fuel Con. vs Price for Highway", xlab = "Price",
ylab = "Miles per Gallon on Highway")
jj <- 0
for(i in levels(cargrp))
{ jj <- jj+1
lines (smooth.spline (price[cargrp==i], mpg.highway[cargrp==i],
spar = spar),
lty = jj, col = jj, lwd = 2)
}
}
my.func()
```
(a) Explain the output generated by the above function call.
(b) What technique can also be followed in the case of point diagrams?
### Adding legends to a graph {#Legends}
(a) Study how the function `legend()` and the graphical parameter `usr` work. Study the code used to obtain Figure \@ref(fig:cargrps). Revise the `locator()` function.
(b) Use the facts that one USA gallon of liquid is equal to $0.83267$ UK (imperial) gallon of liquid and one mile is equal to $1.6093$ kilometres to obtain a figure similar to Figure \@ref(fig:diffLengths) but with a kilometres per litre scale on the right-hand side that corresponds to the miles per gallon (USA) on highway scale on the left-hand side.
```{r, cargrps, fig.cap="Illustrating adding a legend to a plot.", out.width="100%"}
my.func <- function()
{ require (MASS)
oldstate <- par (no.readonly = TRUE)
on.exit (par (oldstate))
cargrp <- Cars93[ , "Type"]
price <- Cars93[ , "Price"]
mpg.city <- Cars93[ , "MPG.city"]
plot(price, mpg.city, type = "n", ylim = c(0, max(mpg.city)),
main = "Fuel Consumption vs Price for City Drive", xlab = "Price",
ylab = "Miles per Gallon in City")
char <- substring (as.character (cargrp), 1, 2)
text (x = price, y = mpg.city, labels = char, pos = 1, cex = 0.75)
labs <- paste (substring (levels (cargrp), 1, 2), levels(cargrp), sep=": ")
legend(x = 40, y = 42, legend = labs)
}
my.func ()
```
### Multiple plots with identical axes {#multAxes}
How can various graphs with identical axes be obtained? Show how this can be done by graphing the sorting time for the three procedures considered in section \@ref(matplot) above in three separate plots in the same graph window.
### Providing a single legend for multiple plots
Suppose there were two sorting methods for each of the three situations described in\@ref(matplot) and \@ref(multAxes) above. How can the three graphs be provided with a single legend without the legend appearing in one of the graphs? Explain in detail.
### Changing the plotting character: common plotting characters in R
Note the use of graphical parameters `pch` and `mkh`. What plotting characters are available? Study the help file of `par()` and `points()`. Study the plotting characters displayed in Figure \@ref(fig:pch) and the code used to produce the figure. How can plotting characters be made to appear in legends?
```{r, pch, fig.cap="Some common plotting characters available in R.", out.width="100%"}
plot (x = rep(1:10, 2), y = rep (c(1,2), c(10,10)), pch = 0:19, cex = 2,
pty = "p", ylim = c(0,3), xlab = "", ylab = "", xaxt = "n", yaxt = "n")
```
### Changing the colour in plots
The graphical parameter `col` allows the user to specify the colour(s) in number format as given in Figure \@ref(fig:col). The full list of named colours can be obtained with the command `colors()` in the Console.
Alternatively, the colour can be specified by hue, saturation and value with `hsv (h = , s = , v = )`, hue, chroma and luminance with `hcl (h = , c = , l = )` or red, green and blue with `rgb (red = , green = , blue = )`. The `rgb()` function has an argument `maxColorValue` with default value `1` which indicates the range known as the gamma-compressed values. Typically, the red, green and blue values range between 0 and 255 or video display or 8-bit graphics. To select a specific shade of light blue, the following command can be used:
```{r, colExample, fig.cap="Colour selection with rgb().", out.width="100%"}
plot (ldeaths, col = rgb (red = 167, green = 227, blue = 227,
maxColorValue = 255))
```
The output of the `rgb()` function is in the hexidemical colour number format, e.g. "#A7E3E3". The function `col2rgb()` accepts a colour name, hexadecimal colour number format or colour number and provides the red, green and blue values in the 0 to 255 range.
```{r, col, echo = FALSE, fig.cap="The default colour palette available in R.", out.width="100%"}
plot (1:8, rep (1, 8), pch = 15, col = 1:8, cex = 3, ylim = c(-1,2),
xaxt = "n", yaxt = "n", xlab = "", ylab = "")
text (1:8, rep (0, 8), 1:8)
```
A sequence of $n$ colours can be generated with the function `colorRampPalette()`. As an example, the colour vector used for plotting in Figure \@ref(fig:colRamp) were generated with the call `colorRampPalette (c ("red", "green", "white", "gold"))(20)`. Study how the following instructions generate colour sequences: `rainbow()`, `heat.colors()`, `terrain.colors()`, `topo.colors()`, `cm.colors()`.
```{r, colRamp, echo = FALSE, fig.cap="User specified colour sequence with colorRampPalette().", out.width="100%"}
col.vec <- colorRampPalette (c ("red", "green", "white", "gold"))(20)
plot (rep(1,20), 1:20, col = col.vec, pch = 15,
xaxt = "n", yaxt = "n", xlab = "", ylab = "")
```
### Logarithmic axes
The `log()` function and the `log` argument of the `plot()` function are useful in this regard. The `log` argument of the `plot()` function can be specified as `log="x"`; or `log="y"`; or `log="xy"` depending on whether the x-axis, the y-axis, or both axes should be plotted logarithmically.
### Graphs with character strings as the ‘scale’ on the axis
Figure \@ref(fig:catAxis) illustrates how user defined character strings can appear as calibrations on an axis. Furthermore, this figure illustrates several techniques to fine-tune plots. Study the code resulting in Figure \@ref(fig:catAxis) in detail.
```{r, catAxis, fig.cap="Figures with character strings as axis calibrations and other enhancements to plots.", out.width="100%"}
my.func <- function()
{ old.state <- par(no.readonly = TRUE)
on.exit (par (old.state))
area <- state.x77[, "Area"]
income <- state.x77[, "Income"]
area.grp <- cut(area, c(0, quantile (area, c(1/3, 2/3, 1))),
labels = c("Small", "Medium", "Large"))
income.grp <- cut(income, c(0, quantile (income, c(1/2, 1))),
labels = c("Below Median", "Above Median"))
mns <- tapply(state.x77[, "Illiteracy"], list(area.grp, income.grp), mean)
par(mfrow = c(1, 2))
plot(c(0.8, 3.2), range(mns), type = "n", xaxt = "n", xlab = "Area Group",
ylab ="Mean Illiteracy", sub = "Function plot() used")
axis(side = 1, at = 1:3, labels = levels(area.grp))
lines(1:3, mns[, 1])
lines(1:3, mns[, 2], lty = 2)
par(usr = c(0, 1, 0, 1))
legend(0.56, 0.96, lty = c(1,2), legend = levels(income.grp), cex= 0.5)
text(0.63, 0.98, adj = 0, "Income Group", cex = 0.5)
interaction.plot(area.grp, income.grp, state.x77[,"Illiteracy"],
xlab = "Area Group", ylab = "Mean Illiteracy",
sub = "Interaction.plot used", lty = 1:2, xtick = TRUE,
legend = FALSE)
par(mfrow = c(1,1))
par(new = T)
plot(1:10, 1:10, type="n", xlab="", ylab="",axes = FALSE)
title(main = "Illiteracy vs Size for States grouped by Income")
}
my.func ()
```
### Customizing bar charts and histograms
(a) How can every bar in a bar chart be represented in a different colour and be given separate headings?
(b) How can only a line graph without any colours be obtained?
(c) How can a probability density function be superimposed on a histogram?
(d) How can bar charts be provided with user-defined axes?
Use the `Cars93` data set to answer the above four questions by constructing a figure similar to the one shown in Figure \@ref(fig:BarHist). Note: In the Mean MPG plot not all car types are used. If a factor variable is subsetted the original levels will be kept although some of them might not occurr. Hence it might be necessary to create a new factor variable with only the levels that are needed by using `factor()`.
```{r, BarHist, echo = FALSE, fig.cap="Enhanced bar charts and histograms.", out.width="100%"}
my.func <- function()
{ require (MASS)
old.state <- par(no.readonly = TRUE)
on.exit (par (old.state))
par (mfrow = c(2,2))
cargrp <- Cars93[,"Type"]
meds <- tapply (Cars93[,"MPG.city"], cargrp, median)
where <- barplot (meds, names = substring (levels(cargrp), 1, 3),
ylim = c(0, max(meds)+10), main = "Bar plot of MG in City",
xlab = "Type of Car", ylab = "Median MPG in City",
col = 1:length(meds), axis.lty = 1)
text (where, meds+3, paste ("n", table (cargrp), sep = "="))
# ---------------------------------------------------------------------------
plot (0:(length(meds)+1), c(rep(0, (length(meds)+1)), max(meds)),
ylim = c(0, max(meds)+10), type = "n", xlab = "",
ylab = "Median MG in City", main = "Bar plot of MPG in City", xaxt = "n")
for (i in 1:length(meds))
lines (c(i,i), c(0, meds[i]), lwd = 2)
title (xlab = "Type of Car")
axis (side = 1, at = 1:6, labels = substring(levels(cargrp), 1, 2))
text (1:6, meds+3, paste("n", table (cargrp), sep = "="))
# ---------------------------------------------------------------------------
weight <- Cars93[,"Weight"]
hist (weight, breaks = seq (from = 1500, to = 5000, by = 500), prob = TRUE,
ylim = c(0, 0.0006), xlab = "Weight", main = "Histogram with normal pdf of Weight")
pts <- seq (from = par("usr")[1], to = par("usr")[2], len = 40)
lines (pts, dnorm(pts, mean=mean(weight), sd=sd(weight)), xpd = TRUE)
# ---------------------------------------------------------------------------
data.use <- Cars93[Cars93[,"Type"] == "Large" |
Cars93[,"Type"] == "Compact" |
Cars93[,"Type"] == "Small", c("Type", "MPG.city", "MPG.highway")]
data.use [,1] <- factor (data.use [,1])
rmeans <- apply (data.use[,2:3], 2, tapply, data.use[,1], mean)
xvals <- barplot (t(rmeans), beside = TRUE, space = c(1.8, 3.5),
main = "Mean MPG", ylab = "Miles per gallon",
names = rep(c("Cit","Hwy"), 3), col = 3:4)
axis (side = 1, at = apply (matrix (xvals, nrow = 2), 2, mean),
line = 1, labels = rownames(rmeans), tick = FALSE)
abline (h = 0)
}
my.func ()
```
### Three-dimensional graphical displays
(a) Study how the function `persp()` works.
(b) Work through the example code that creates Figure \@ref(fig:persp). Apart from the arrow that points to the maximum, different colours must be used to highlight the different aspects of the graph.
(c) Provide horizontally and vertically rotated views of the 3D plot.
```{r, persp, fig.cap="Annotated 3D perspective plot.", out.width="100%"}
my.func <- function ()
{ x <- seq(-10, 10, length= 30)
y <- x
ff <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, ff)
z[is.na(z)] <- 1
op <- par(bg = "white")
# persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")
res <- persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
ltheta = 120, shade = 0.75, ticktype = "detailed", xlab = "X",
ylab = "Y", zlab = "Z" )
print (round(res, 3))
#--- Add to existing persp plot : ---
#--- Function trans3d() -------------
trans3d <- function(x,y,z, pmat)
{
tr <- cbind(x,y,z,1) %*% pmat
list(x = tr[,1]/tr[,4], y = tr[,2]/tr[,4])
}
# ----------------------------------
z1 <- ff(1e-10, 1e-10)
transfrm <- trans3d (c(0,-2.5), c(0,5), c(z1,z1), res)
arrows(transfrm$x[1], transfrm$y[1], transfrm$x[2], transfrm$y[2],
length = 0.1, code = 1)
text(transfrm$x[2], transfrm$y[2]+0.02, "Maximum occurs here")
return(z1)
}
my.func()
```
### Diagrams
Use R to draw a simple flow diagram. The diagram must contain at least one rectangle, one square, one circle and one triangle. Furthermore, there must be straight and curved lines as well as text describing the different elements. *Hint*: Study how the functions `arrows()`, `lines()`, `text()` and `symbols()` work as discussed in their respective help facilities.
### Annotating graphics with special symbols
Construct a graph of a $normal(0, 1)$ density function. Give as a title to the plot the expression "Density of a normal random variable with $\mu = 0$ and $\sigma^2 = 1$." *Hint*: Consult the help file of `plotmath()`. Within the plot draw an arrow to the density and label it $\frac{1}{\sqrt{2 \pi}} e^{-\frac{1}{2}x^2}$.
## Quantile plots {#qqplot}
Consider the histogram of weight in Figure \@ref(fig:BarHist). Does this variable follow a normal distribution? A normal quantile plot, shows the observations vs the corresponding quantiles of a standard normal distribution. If the observations correspond to a normal distribution, this will approximately form a straight line. Use the `qqline()` function to add a straing line to the plot.
```{r, qq_norm}
qqnorm (Cars93$Weight)
qqline (Cars93$Weight)
```
In a similar manner, quantile-quantile plots for other probability distributions can be constructed with the function `qqplot()`.
```{r, qq_other}
y <- rexp(200, rate=4)
qqplot (qexp (seq (from = 0, to = 1, len = 200), rate=4), y)
qqline(y, distribution = function(p) qexp(p, rate=4))
```
## Estimating a density {#density}
The histograms in Figure \@ref(fig:histDiffBins) show 200 observations generated, 100 from a $normal (9,2^2)$ and 100 from a $normal (13,1)$ distribution. Histograms are very sensitive to the choice of the number of bins and the starting values of the bins. The wider bins do not show any evidence of a bimodal distribution. Using the smaller bins, the location of the bins can suggest either a bimodal or trimodal distribution.
```{r, histDiffBins, echo = FALSE, fig.cap="Histograms with different bin sizes and bin locations of the same normal mixture data set.", out.width="100%"}
set.seed (38472)
x1 <- rnorm(100, 9, 2)
x2 <- rnorm(100, 13, 1)
x <- c(x1, x2)
par(mfcol=c(2,3))
out1 <- hist(x,right=F)
out2 <- hist(x,breaks=20,right=F)
b1 <- out1$breaks
b11 <- c(b1[1]-0.5,b1+0.5)
b2 <- out2$breaks
b21 <- c(b2[1]-0.5,b2+0.5)
hist(x,breaks=b11,right=F)
hist(x,breaks=b21,right=F)
b12 <- c(b1[1]-0.2,b1+0.2)
b22 <- c(b2[1]-0.2,b2+0.2)
hist(x,breaks=b12,right=F)
hist(x,breaks=b22,right=F)
```
One possible solution to the bin selection problem for histograms is the Average Shifted Histogram (ASH). First we define a *<span style="color:#FF9966">density histogram</span>*. Since we aim to estimate the density (which integrates to one) a density histogram is normalised such that the area in the histogram is equal to one.
Consider a set of bins $B_k=[b_k, b_{(k+1)})$ with fixed bin width $λ=b_{(k+1)}-b_k$ $∀ k$, then the density histogram is defined as $\hat{f} = \frac{1}{N\lambda} \sum_{i=1}^{N}{I_{[b_k,b_{k+1})}(x_i)}$ for $x∈B_k$. Consider a collection of $m$ histograms $\hat{f}_1, \hat{f}_2, \dots, \hat{f}_m$ each with bin width $h$, but with respective bin origins $b_{01}=0, b_{02}=\frac{h}{m}, b_{03}=\frac{2h}{m}, \dots, b_{0m}=\frac{(m-1)h}{m}$. The *<span style="color:#FF9966">average shifted histogram</span>* is defined as $\hat{f}_{ASH} = \frac{1}{m} \sum_{i=1}^{m}{\hat{f}_i}$.
```{r, ASH, fig.cap="Average shifted histogram of normal mixture data.", out.width="100%"}
ASH <- function (x, b0 = 1, bk = 15, h = 0.5, m = 5) # h=lambda
{
Bvec <- as.vector ((bk - b0)/h+2, "list")
fhat <- matrix (nrow = m, ncol = (bk-b0)/h+1)
for (i in 1:m)
{ Bvec[[i]] <- seq (from = b0+(i-1)*h/m, to = bk+h+(i-1)*h/m, by = h)
fhat[i,] <- hist (x, breaks = Bvec[[i]], right = T, plot = F)$density
}
fhat.ASH <- apply(fhat, 2, mean)
x.vec <- seq (from = b0, to = bk+h,length = length(fhat.ASH))
plot (x.vec, fhat.ASH, type="l")
}
ASH(x, m=20, h=1, b0=-2, bk=18)
```
The ASH is given in Figure \@ref(fig:ASH) A more sophisticated method for estimating a density is with a kernel density estimate. The density histograms is replaced by a smooth kernel function, leading to a smoother estimate. The R function `density()` provides a variety of kernels. Using the default kernel, a Gaussian distribution, the kernel density estimate is given in Figure \@ref(fig:densityExample).
```{r, densityExample, fig.cap="Guassian kernel density estimate of the normal mixture data.", out.width="100%"}
plot(density(x), type="l")
```
Experiment with different kernel function and different choices of bandwidth (argument bw) for controlling the amount of smoothing.
## A coplot with two conditioning variables {#coplot}
Consider the `state.x77` data set. In section \@ref(highLevelPlotting) the `coplot()` function was used to construct a plot of `Illiteracy` and `Area` conditional on `Income`. This can be expanded to two conditions, for example plotting `Illiteracy` and `Life expectancy` conditional on `Income` and `Area`. Interpret. The number of panels and overlap of given intervals can be controlled with the arguments number and overlap.
```{r, condIncomeArea}
coplot (state.x77 [,"Illiteracy"] ~ state.x77 [,"Life Exp"] |
state.x77 [,"Income"] + state.x77 [,"Area"],
number = c(4,3), overlap=c(0,0.2))
```
## Exact distances in graphics
(a) Obtain a random sample of size 50 from a bivariate normal distribution with $n(50,20)$ marginals and a correlation coefficient of 0.90.
* Present the data in the form of a scatterplot.
* Next, write an R function to perform the following task on the scatterplot:
* Choose an arbitrary point and label it “A”.
* Draw a line connecting A to a circle with centre exactly 25mm away from A. The diameter of the circle must be exactly 40mm.
* Label the centre point of the circle with a “B”.
* Use a ruler to check the length of the connecting line and diameter of the circle.
* Obtain a print copy of the graph and check the lengths again.*Hint*: Study the help file of function `par()`.
(b) Use R to make a ruler calibrated in centimetres from zero to 15 cms.
## Multiple graphics windows in R
(a) Study how the following instructions work to control multiple graphics windows in R:
```{r, newWindows, eval = FALSE}
dev.new()
dev.list()
dev.set()
dev.next()
dev.cur()
dev.copy()
dev.prev()
dev.off()
dev.ask()
graphics.off()
```
(b) Study the information that R gives via the execution of `help.search ("graph")`.
## More complex layouts
Study the graphical requirements needed for constructing Figure \@ref(fig:complexLayout) and how to code these requirements.
```{r, complexLayout, fig.cap="A complex graphics layout.", out.width="100%"}
my.func <- function ()
{ old.state <- par (no.readonly = TRUE)
on.exit (par (old.state))
par (omd = c(0, 0.66, 0, 1), mfcol = c(2, 1))
ts.plot (mdeaths, xlab = "Year", ylab = "Male deaths")
ts.plot (fdeaths, xlab = "Year", ylab = "Female deaths")
par (omd = c(0.66, 1, 0, 1), mfcol = c(2, 1), mfg = c(1, 1), new=TRUE)
hist (mdeaths, xlab = "Male deaths", ylab = "Frequency", main = "")
hist (fdeaths, xlab = "Female deaths", ylab = "Frequency", main= "")
par (omd = c(0, 1, 0, 1), mfcol = c(1, 1))
title ("Line plot and Histogram for male deaths")
par(omd = c(0, 1, 0, 0.5), mfcol = c(1, 1))
title ("Line plot and Histogram for female deaths")
}
my.func ()
```
## Dynamic 3D graphics in R
* Study the R package `rgl`.
* Attach library `rgl` to the search path and then issue the R command `example (plot3d)`. Use the mouse buttons to rotate and zoom the rgl graph.
* Next, issue the R command `example (surface3d)` and interactively explore the 3D figure.
## Animation
Study the following two functions in detail:
```{r, animation, eval = FALSE}
anim1 <- function (sleep = 0.05)
{ # Press ESC to end animation
n <- 40
t <- seq (0, 2*pi, length = n)
x <- cos(t)
y <- sin(t)
for (i in 1:n)
{ plot.new ()
plot.window (c(-1, 1), c(-1, 1), asp = 1)
points (x[i], y[i], pch = 16, cex = 2)
Sys.sleep(sleep)
#Sys.sleep() suspends execution for a given number of seconds
}
Recall(sleep)
}
anim2 <- function (sleep = 0.01)
{ for (i in seq (from = 1, to = 3, by = 0.01))
{ plot.new ()
plot.window (c (1, 16), c(1, 16), asp = 1)
arrows(2*i, 2*i, 4*i, 4*i)
Sys.sleep(sleep)
}
Recall(sleep)
}
```
Write an R function to show a wheel with two spokes moving forward with adjustable speed.
## Exercise {#Ex10}
::: {style="color: #80CC99;"}
(1) In many real life situations it is necessary to identify an object when only limited information is available. The following problem how such a problem can be empirically investigated.
<div style="margin-left: 25px; margin-right: 20px;">
The function `persp()` used for constructing Figure \@ref(fig:persp) requires a regular pattern of $x$ and $y$ coordinates. If such a pattern is not available it is necessary to interpolate e.g. with `interp()` (available in package `akima`) using the available values.
Use the function `expand.grid()` to create a grid of regularly spaced $x$ and $y$ values and evaluate the “sombrero” function of Figure \@ref(fig:persp) at each of these points.
Now use `sample()` to randomly sample points from that grid and then the `interp()` function to interpolate the values of z throughout the grid.
Finally, use `persp()` to construct a plot of the interpolated values.
What fraction of data is needed in the sample to get a good representation of the true shape of the data. *Hint*: since `persp()` does not accept `NA`s replace `NA`s with the minimum of the non-missing z values.
</div>
(2) Use `locator()` and write a function to allow placing a legend with a pointing device anywhere on an existing plot.
(3) Use the `state.x77` data set to construct a scatterplot of `Illiteracy` as a function of `Income`. Now construct a second scatterplot of the same data but with the origin on the right-hand side of the x-axis. In order to complete this task it is necessary that the values on the x-axis increase from the left-hand side to the right-hand side.
(4) Consider the following data
| | Test 1 | Test 2 | Test 3 | Test 4 |
| ------- | --------| ------- | --------| --------|
| Group A: | 10 | 15 | 30 | 12 |
| Group B: | 125 | 130 | 148 | 115 |
<div style="margin-left: 25px; margin-right: 20px;">
Plot the data of the two groups in the form of two profiles on the same set of axes.
Plot the data against Test 1, Test 2, Test 3 and Test 4 on the x-axis.
The scale of the data of Group A must appear on the y-axis on the left-hand side and that of Group B on the y-axis on the right-hand side. A detailed legend must be provided.
</div>
:::
## The package ggplot2
The package `ggplot2` is based on the ideas of @Wickham2010 as described in the paper “A layered grammar of graphics” and makes use of the The Grammar of Graphics by @Wilkenson2005.
```{r, ggplotStructure, echo=FALSE, fig.cap="Layer structure of ggplot2 package.", out.width="100%"}
library(knitr)
knitr::include_graphics("pics/ggplot.jpg")
```
In Figure \@ref(fig:ggplotStructure)(a) the components of a *<span style="color:#FF9966">layer</span>* is depicted. The first essential component is the *<span style="color:#FF9966">data</span>* to be represented in the graphic. Together with the data, there needs to be an *<span style="color:#FF9966">aesthetic mapping</span>*, describing which variable is mapped to the x-direction, y-direction, the size, shape, colour, etc. The *<span style="color:#FF9966">statistics</span>* component optionally transforms the data to quantities that needs to be plotted. Typically, the transformation is used to summarise the data. It is possible to map aesthetics to these new variables. The *<span style="color:#FF9966">geometry</span>* defines how each aesthetic is displayed, as points, lines, boxplots, densities, histograms, etc. Each geometry can only display specific aesthetics, for example a point has position, colour, shape and size. Position adjustment is needed in cases where geometric elements overlap, for example using jitter in scatterplots or placing multiple bars stacked or side-by-side in a barplot.
A graphic can consist of several layers, as shown in Figure \@ref(fig:ggplotStructure)(b). According to the grammar of graphics, a *<span style="color:#FF9966">scales</span>* component needs to be specified. The scales are common across layers and describe the mapping of the data to aesthetic attributes such as which colour is associated with which level of a categorical variable. One scale is needed for each aesthetic property used in the layers. In order to place the geometric objects on the plotting plane, a scale is needed. The most commonly used scale is the Cartesian axes, while others such as polar coordinates is also available.
*<span style="color:#FF9966">Faceting</span>* splits the data into small multiples of different subsets of the data set. With this component we identify the variable(s) for splitting and how the splitting should be arranged. *<span style="color:#FF9966">Themes</span>* are not linked to the data but provide instructions on aspects such as titles, labels, fonts, background, gridlines, and legends.
The full specification of all the components in a ggplot, can be very cumbersome. Defaults are specified, for instance for each geometry there is a default statistic and for each statistic a default geometry. We can therefore build our plot stepwise, fine-tuning detailed aspects until the required graphic is obtained.
We will start with some simple plots and then build more complicated graphics. We will use the `cereal` tibble created from the `UScereal` data in package `MASS` (see section \@ref(dplyr)) for illustration.
```{r, cerealCh10}
library (MASS)
library (tidyverse)
cereal <- tibble (UScereal)
```
### Barplot
The command
```{r, ggplotBarplot}
ggplot(data = cereal,
mapping = aes(x = mfr)) +
geom_bar()
```
produces a simple barplot of the `cereal` data with `mfr` on the x-axis and counts of each level in the `bars`. No position adjustments are made, while the default colour for the bars is used to plot the complete data set on Cartesian axes with the default theme.
We can change the colour of the bars with the command
```{r, ggplotBarplot2}
ggplot(data = cereal,
mapping = aes(x = mfr)) +
geom_bar(fill = "gold")
```
Now we add an aesthetic for the bars to be coloured according to the vitamin enrichment, while at the same time, changing the orientation. Note that in the previous example, the fill colour was specified outside of the function `aes()`, while here, it is specified as an aesthetic.
```{r, ggplotBarplot3}
ggplot(data = cereal,
mapping = aes(y = mfr, fill = vitamins)) +
geom_bar()
```
The default is to stack the bars. In order to position the bars side-by-side we use the function `position_dodge()`.
```{r, ggplotBatplot4}
ggplot(data = cereal,
mapping = aes(y = mfr, fill = vitamins)) +
geom_bar(position = position_dodge())
```
### Scatterplot
The simplest call to produce a scatterplot uses the identity statistical transformation with no position adjustment on the complete data set with default size, shape and colour of the plotting characters.
```{r, ggplotScatter}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point()
```
The point colours can be specified either according to a categorical variable, or a spectra based on a continuous variable.
```{r, ggplotScatter2}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = factor(shelf)))
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars))
```
A scatterplot smoother can be added to our plot with the function `geom_smooth()`.
```{r, ggplotScatter3}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars)) +
geom_smooth()
```
The smooth function can also be a linear regression line.
```{r, ggplotScatter4}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars)) +
geom_smooth(method = "lm")
```
To add different sizes and shapes according to `shelf` and `mfr`, respectively, we need the command
```{r, ggplotScatter5}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars,
shape = mfr,
size = factor(shelf)))
```
Finally, since there are multiple observations with zero fat, we want to jitter the observations in the vertical direction with a random amount in the interval $±0.05$.
```{r, ggplotScatter6}
ggplot(data=cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping=aes(colour = sugars),
shape = "cross",
position = position_jitter(height=0.05))
```
The `geom_text()` and `geom_label()` functions are useful to replace plotting characters with sample names or a specified label.
```{r, ggplotScatter7}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_text(mapping = aes(label=mfr))
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_text(mapping=aes(label=mfr), check_overlap=T)
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_label(mapping = aes(label=mfr))
```
### Dotplot
Below a simple dotplot of the carbo variable followed by another dotplot with several tweaks in presentation.
```{r, ggplotDot}
ggplot (data = cereal, mapping = aes(x = carbo)) +
geom_dotplot()
ggplot (data = cereal, mapping = aes(x = carbo)) +
geom_dotplot(binwidth = 2, stackdir = "center",
stackratio = 0.8, dotsize = 1.2)
```
### Boxplot
The `geom_boxplot()` function allows us to make a simple boxplot. However, below we make several boxplots according to vitamin enrichment and overlay the observed data.
```{r, ggplotBoxplot}
ggplot (data = cereal,
mapping = aes(x = vitamins, y = sodium)) +
geom_boxplot() + geom_jitter()
ggplot (data = cereal,
mapping = aes(x = vitamins, y = sodium)) +
geom_boxplot() + geom_jitter()
```
### Line plot
To illustrate plotting lines with `ggplot2` we will create a small data set $y_a=log(x)$ and $y_b=2log(x)$ with $0 < x< 1$.
```{r, ggplotLine}
x <- seq(from = 0.01, to = 0.99, len = 100)
y <- c(log(x), 2 * log(x))
z <- rep(c("a", "b"), each = 100)
dat <- tibble(x=rep(x,2), y, z)
dat
ggplot(dat, aes(x = x, y = y)) +
geom_line(aes(colour = z))
```
### Density estimates
Non-parametric density estimates are useful to summarise the distribution of data. For a single variable, the `geom_density()` function produces a density estimate (see section \@ref(density)). Here we illustrate the use of the two-dimensional density estimate with the function `geom_density_2d()` and the Old Faithful data from package `datasets`. Note that the call to `ggplot()` is written to the object `p1`. The content of `p1` is the plot. Assigning the name `p1` to the plot prevents having to retype the full call for every subsequent execution.
```{r, ggplotDensity}
p1 <- ggplot (faithful,
aes(x = eruptions, y = waiting)) +
geom_point() + xlim(0.5,5) + ylim(40,110)
p1
p1 + geom_density_2d()
```
In the above examples, the geometry is specified, without any specification of statistical transformations. Although not specified explicitly, statistical transformations are performed. For instance in the barplot above, the `stat_count()` is the default for `geom_bar()` to determine the frequencies plotted on the vertical axis. In most instances, the default `stat_xxx()` function is appropriate for the particular `geom_yyy()` function and specifying other statistical transformations could lead to non-sensicle calls. In most calls to `ggplot()`, the default `stat_xxx()` is appropriate and not explicitly specified. Below, we look at a few exceptions.
### Empirical cumulative distribution function
The empirical cumulative distribution function also provide details on the shape of the distribution underlying the observations and can be plotted with `stat_ecdf()`.
```{r, ggplotEcdf}
n.1.1 <- rnorm(100, 1, 1)
F.4.9 <- rf(100, 4,9)
dat <- tibble(n.1.1,F.4.9)
dat2 <- pivot_longer(dat, cols = everything())
ggplot (dat, aes(x=n.1.1)) + stat_ecdf()
ggplot (dat2, aes(x=value, colour = name)) + stat_ecdf()
```
### Mathematical functions
Any function $f(x)$ can be plotted, or added to a plot with `stat_function()`. First we will plot the function $f(x)=2e^xcos(x)$.
```{r, ggplotfx}
p2 <- ggplot() + xlim(-5,5)
p2 + geom_function(fun = function(x) 2*exp(x)*cos(x))
```
Next we will compare our empirical cumulative distribution function, to the cumulative distribution functions of a Poisson and normal distribution. (Remember, the normal distribution provides an approximation to the Poisson).
```{r, gglotfx2}
x3 <- rpois(100, 5)
dat3 <- tibble(x3)
ggplot (dat3, aes(x = x3)) + stat_ecdf() +
geom_function(fun = ppois,
args=list(lambda=mean(x3)), col="blue") +
geom_function(fun = pnorm,
args=list(mean=mean(x3), sd=sqrt(mean(x3))),
col="red")
```
### `after_stat()` function
When constructing a histogram, the frequencies appear on the vertical axis. These frequencies are the output of the function `stat_bin()` which means they are not available up front in the data set itself. The `after_stat()` function allows us to use the computed variables, for instance to scale the histogram to area $=1$ in order to compare the observed distribution to a theoretical probability density function.
```{r, ggplotAfterstat}
x4 <- rgamma(1000, 5, 3)
dat4 <- tibble(x4)
ggplot (dat4, aes(x4)) + geom_histogram()
ggplot(dat4, aes(x4)) +
geom_histogram(aes(y=after_stat(density)),
fill="pink") +
geom_function (fun = dgamma,
args=list(shape = 5, rate = 3))
```
### Scales
The scales link the aesthetic attributes such as colours, plotting characters, line types, axis scales etc. to the data. Implicitly, in all the calls above, default scales are specified. Should we wish to change the defaults, the scales need to be specified explicitly.
In the call
```{r, ggplotScales}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = mfr))
```
different colours are assigned to the points, based on the content of `mfr`. Since `mfr` is a categorical variable with six levels, the first six default colours are used. The user can specify their own colour selection with the function `scale_colour_manual()`. However, the Brewer palettes are convenient colour schemes designed by Cynthia Brewer as described at
<http://colorbrewer2.org>. Below a qualitative scale is used according to the levels of `mfr`.
```{r, ggplotScales2}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = mfr)) +
scale_colour_brewer(type = "qual")
```
Next, we will define our own gradient fill scaling for use with the continuous variable `sugars`. The default scale ranges from light blue to dark blue.
```{r, ggplotScales3}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars))
```
The built in colour palettes `hcl.colors`, `hcl.pals`, `rainbow`, `heat.colors`, `terrain.colors`, `topo.colors` and `cm.colors` can be selected with the function `scale_colour_gradientn()` or `scale_fill_gradientn()`.
```{r, ggplotScales4}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars))+
scale_colour_gradientn(colours = rainbow(21))
```
The functions `scale_colour_gradient()` and `scale_fill_gradient()` allows the user to specify a two-colour gradient scale while `scale_colour_gradient2()` and `scale_fill_gradient2()` allows for specification of a three-colour gradient scale.
```{r, ggplotScales5}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars))+
scale_colour_gradient(low = "black",
high = "orange")
```
In a final example of scales we will change the vertical axis to a log scale while changing the axis markers on the horizontal scale.
```{r, ggplotScales6}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +
geom_point(mapping = aes(colour = sugars))+
scale_colour_gradient(low = "black",
high = "orange") +
scale_x_continuous(breaks = seq(from = 50, to = 450, by = 50)) +
scale_y_continuous(trans = "log")
```
### Coordinates
By default, all the plots we have made are on the Cartesian axes. One alternative would be to use a polar coordinate system.
```{r, ggplotCoords}
# Hadley's favourite pie chart
df <- data.frame(
variable = c("does not resemble", "resembles"),
value = c(20, 80)
)
ggplot(df, aes(x = "", y = value, fill = variable)) +
geom_col(width = 1) +
scale_fill_manual(values = c("red", "yellow")) +
coord_polar("y", start = pi / 3) +
labs(title = "Pac man")
```
To plot the function $f(\theta)=\theta sin(\theta)$, $0 \le \theta \le \frac{\pi}{2}$ we need to following code:
```{r, ggplotCoords2}
theta.vec <- seq(from = 0, to = pi/2, len = 200)
my.dat <- tibble (theta = theta.vec,
r = theta.vec*sin(theta.vec))
ggplot (my.dat) + geom_line(aes(x = theta, y=r)) +
coord_polar(theta = "x")
```
As illustrated in Exercise \@ref(Ex6) number 10 it is sometimes essential to keep the aspect ratio in the graphic fixed, usually at $1:1$. Classical scaling is a method to produce a map from a given matrix of pairwise distances. In the code below, a map (subject to rotation and reflection) of cities in Europe is produce with the function `cmdscale()`. In order to visually assess intercity distances, it is important to have one unit in the horizontal direction equal to one unit in the vertical direction. This is achieved with `coord_fixed (ratio = 1)`.
```{r, ggplotCoords3}
city.coords <- data.frame(city=attr(eurodist,"Labels"),
cmdscale(eurodist))
colnames(city.coords)[2:3] <- paste("dim",1:2,sep="")
city.coords <- tibble(city.coords)
ggplot (city.coords, mapping = aes(x = dim1, y = dim2)) +
geom_text(mapping = aes(label=city)) +
coord_fixed(ratio = 1)
```
### Facets
Facets allows for the grouping of the data set into smaller similar data sets. We can plot the `fat` vs `calories` for every manufacturer separately.
```{r, ggplotFacets}
ggplot(data = cereal,
mapping = aes(x = calories, y = fat)) +