forked from bcb420-2022/R_basics
-
Notifications
You must be signed in to change notification settings - Fork 1
/
12-R-plotting.Rmd
702 lines (498 loc) · 16.5 KB
/
12-R-plotting.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
# Introduction to R Plots {#r-plots}
(Introduction to R plots)
## Overview
### Abstract:
Introductory concepts and exercises for creating graphics with R.
### Objectives:
This unit will:
* introduce concepts of graphics for data visualization and descrptive statistics;
* teach basic plotting methods;
### Outcomes:
After working through this unit you:
* know where to find models of good data visualization;
* can create and customize basic plots in R;
### Deliverables:
**Time management**: Before you begin, estimate how long it will take you to complete this unit. Then, record in your course journal: the number of hours you estimated, the number of hours you worked on the unit, and the amount of time that passed between start and completion of this unit.
**Journal**: Document your progress in your Course Journal. Some tasks may ask you to include specific items in your journal. Don't overlook these.
**Insights**: If you find something particularly noteworthy about this unit, make a note in your insights! page.
### Prerequisites
[RPR-Functions (R Functions)](#r-functions)
`r task_counter <- task_counter + 1`
## Task `r task_counter`
```{block, type="rmd-task"}
* Read the introductory notes on [graphics in R](boris_docs/RPR-Plotting.pdf), and some concepts of graphics for descriptive statistics.
* Load the R-Exercise_BasicSetup project in RStudio if you don't already have it open.
* Type init() as instructed after the project has loaded.
* Work through the plottingIntro.R script.
```
## Types of plots
This lists the generic plots only. Many more specialized plot-types are available.
* plot()
* pie()
* hist()
* stripchart()
* stem()
* barplot()
* boxplot()
### plot()
```{r}
?plot
```
```{r}
# generate some data to plot
x <- rnorm(200)
y <- x^3 * 0.25 + rnorm(200, 0, 0.75)
?plot
# standard scatterplot
plot(x,y)
```
```{r}
plot(x,y)
# Add a rug representation:
rug(x)
rug(y, side=2, col="red")
```
### barplot()
```{r}
?barplot
barplot(table(round(y)))
```
### hist()
```{r}
?hist
set.seed(12357)
x <- rnorm(50)
hist(x, breaks=5)
```
```{r}
hist(x, breaks=5)
# add a stripchart() of the actual values
stripchart(x, pch="|", add=TRUE, col="red3", xlim=c(-3, 3), at=-0.5)
```
**Note:** a similar plot for bivarite data is achieved with the rug() function.
assigning the output of hist() makes the values used in constructing the histogram accessible:
```{r}
info <- hist(x, breaks=5)
info
```
we can explicitly set breakpoints in a vector:
* here we set them at 0.5 sigma intervals from -3 to 3
```{r}
s <- 1.0
hist(x, breaks=seq(-3*s, 3*s, by=0.5*s))
```
```{r}
# we can colour the bars individually...
hcol <- c("#4F47FD", "#6982FC", "#8AA6EF", "#AFBBDB", "#BEBEBE", "#A9A9A9",
"#A9A9A9", "#BEBEBE", "#DBBBAF", "#EFA68A", "#FC8269", "#FD474F")
# Most parameters of a generic plot apply.
h <- hist(x, breaks=seq(-3*s, 3*s, by=0.5*s),
col=hcol,
main="",
xlab=expression(sigma),
ylab="Counts")
# ... and we can add the individual counts to the plot.
text(h$mids, h$counts, h$counts, adj = c(0.5, -0.5), col = hcol)
```
### boxplot
```{r}
?boxplot
x <- rnorm(200)
boxplot(x)
```
```{r}
m <- x
m <- cbind(m, x^2)
m <- cbind(m, x^3)
m <- cbind(m, x^4)
m <- cbind(m, x^5)
boxplot(m)
```
```{r}
boxplot(log(abs(m)))
```
### Colour
Colours can be specified by number, by name, as hex-triplets as rgb or hsv values, and through colour palettes.
#### Colours by number
The col=... parameter for plots is 1 by default and you can set it to the range 0:8.
* 0: white
* 1: black (the default)
* 2: red
* 3: green
* 4: blue
* 5: cyan
* 6: magenta
* 7: yellow
* 8: grey
```{r}
barplot(rep(1,9), col=0:8, axes=FALSE, names.arg=c(0:8))
```
As you can see, these primary colours are decidedly garish and offend even the most rudimentary sense of aesthetics. Fortunately there are much more sophisticated ways to define colours in R.
#### 2.2 Colours by name
You may have noticed that "red", "green", and "blue" work for the col=... parameter, but you probably would not have imagined that "peachpuff", "firebrick" and "goldenrod" are valid as well. In fact, there are 657 named colours in R. Access them all by typing:
```{r}
colors()
```
```{r}
pie(c(1, 1, 2, 3, 5, 8, 13),
col=c(
"firebrick2",
"tomato",
"goldenrod1",
"peachpuff",
"papayawhip",
"seashell",
"whitesmoke"
)
)
```
Read more about named colours (and related topics) [here](http://research.stowers.org/mcm/efg/R/Color/Chart/)
#### Colours as hex-triplets
Hex triplets in **R** work exactly as in HTML: a triplet of RGB values in two-digit hexadecimal representation. The first two digits specify the red value, the second two are for green, then blue. R accepts a fourth pair of digits to optionally specify the transparency, the semantics of the code is thus "#RRGGBB" or "#RRGGBBAA". Read more e.g. at http://en.wikipedia.org/wiki/Web_colors
```{r}
# The function col2rgb() converts colour names to rgb values ...
col2rgb("violetred")
```
```{r}
# ... and rgb() converts rgb values to hex-code:
rgb(1, 0.5, 0.23)
```
Unfortunately the output of col2rgb does not quite match rgb(). col2rgb creates rows with values between 0 and 255, and rgb by default expects columns with intensities from 0 to 1, you have to transpose and divide.
```{r}
rgb(t(col2rgb("red"))/255) # "#FF0000"
rgb(t(col2rgb("peachpuff"))/255) # "#FFDAB9"
```
There are many tools on the Web that help to generate pleasing palettes.
Here is an example -"Creative Cloud"- taken from https://kuler.adobe.com/
```{r}
CC <- c("#011640", "#024059", "#F2F0D0", "#BE6C5C", "#8C3037" )
hist(rnorm(1000), breaks=20 , col=CC)
```
**R** colours are actually specified as quartets: the fourth value the "Alpha channel" defines the transparency. Setting this to values other than "FF" (the default) can be useful for very crowded plots, or for creating overlays.
```{r}
x <- rnorm(2000)
y <- x^3 * 0.25 + rnorm(2000, 0, 0.75)
```
compare:
```{r}
plot(x,y, pch = 19, col = "#EE3A8C")
```
And
```{r}
plot(x,y, pch = 19, col = "#EE3A8C12") # Alpha at ~ 10%
```
or with multiple overlays of varying size using points() ...
```{r}
plot( x,y, pch = 16, cex = 1, col = "#AA330009")
```
```{r}
plot(x,y, pch = 19, cex = 2, col = "#44558803")
```
```{r}
plot(x,y, pch = 20, cex = 0.5, col = "#EE3A8C08")
```
A similar behaviour can be obtained from "density adapted colors with the densCols() function
```{r}
plot (x, y, col = densCols(x, y), pch = 19, cex = 1.5)
```
### Colour palettes
R has several inbuilt colour palettes, or you can build your own.
```{r}
# Inbuilt palettes
?rainbow
```
* view the palettes
```{r}
opar <- par(mfrow=c(3,2))
n <- 20
sq <- rep(1, n)
barplot(sq, col=rainbow(n), axes=F, main="rainbow(n)")
barplot(sq, col=cm.colors(n), axes=F, main="cm.colors(n)")
barplot(sq, col=topo.colors(n), axes=F, main="topo.colors(n)")
barplot(sq, col=terrain.colors(n), axes=F, main="terrain.colors(n)")
barplot(sq, col=heat.colors(n), axes=F, main="heat.colors(n)")
par <- opar
```
Useful palettes have also been described specifically for cartography. [Colorbrewer2](http://colorbrewer2.org/) has palettes for seqential and qualitative diferences, and options for colourblind-safe and photocopy friendly palettes. You can use them via an **R** package:
```{r}
if (!require(RColorBrewer, quietly=TRUE)) {
install.packages("RColorBrewer")
library(RColorBrewer)
}
display.brewer.all()
```
Here, we apply a Brewer palette to a Voronoi tesselation of a point set.
```{r}
if (!require(deldir, quietly=TRUE)) {
install.packages("deldir")
library(deldir)
}
```
Create a point set along a logarithmic spiral, with a bit of added noise.
```{r}
li <- 0.1
n <- 45
dl <- 1.06
ncirc <- 13
da <- (2*pi)/ncirc
fnoise <-0.13
```
create a matrix of points
```{r}
x <- numeric(n)
x <- cbind(x, numeric(n))
set.seed(16180)
for (i in 1:n) {
l <- li * (dl^(i-1))
x[i,1] <- (l+(rnorm(1)*fnoise*l)) * cos((i-1)*da)
x[i,2] <- (l+(rnorm(1)*fnoise*l)) * sin((i-1)*da)
}
plot(x[,1], x[,2])
```
```{r}
ts <- deldir(x[,1], x[,2]) # calculate the tesselation
tl <- tile.list(ts) # calculate the list of tiles
plot.tile.list(tl) # plot it
```
Let's colour the cells by distance from a defined point using a Brewer palette
```{r}
plot.tile.list(tl) # plot it
points(x[25,1], x[25,2], pch=20, col="red") # pick a point
vec <- c(x[25,1], x[25,2]) # define a point
```
define a function for Euclidian distance
```{r}
vDist <- function(x,v) { sqrt(sum((x-v)^2)) } # calculates Euclidian distance
d <- apply(x, 1 , vDist, v=vec) # apply this to the point set
dCol <- floor(((d-min(d))/(max(d)-min(d)) * 10)) + 1 # map d into 10 intervals
dCol[which(dCol>10)] <- 10 # demote the largest one
pal <- brewer.pal(10, "RdGy") # create the palette
# plot the tesselation, colour by palette
plot.tile.list(tl, fillcol = pal[dCol], cex=0.8, pch=20, col.pts="slategrey")
```
## Lines
Basically all plots take arguments lty to define the line type, and lwd to define line width
```{r}
# empty plot ...
plot(c(0,10), c(0,10), type = "n", axes = FALSE, xlab = "", ylab = "")
# Line type
for (i in 1:8) {
y <- 10.5-(i/2)
segments(1,y,5,y, lty=i)
text(6, y, paste("lty = ", i), col="grey60", adj=0, cex=0.75)
}
# Line width
for (i in 1:10) {
y <- 5.5-(i/2)
segments(1,y,5,y, lwd=(0.3*i)^2)
text(6, y, paste("lwd = ", (0.3*i)^2), col="grey60", adj=0, cex=0.75)
}
```
## Axes
```{r}
# For Details, see:
?plot.default
```
```{r}
n <- 1000
x <- rnorm(n)
y <- x^3 * 0.25 + rnorm(n, sd=0.75)
plot(x,y) # Default
```
```{r}
plot(x,y, xlim=c(-4, 4)) # fixed limits
```
```{r}
plot(x,y, xlim=c(-4, 4), ylim=c(10, -10)) # reverse is possible
```
```{r}
plot(x,y, log="xy") # log axes
```
The axis parameters in the default plot are limited. If you want more control, suppress the printing of an axis in the plot and use the axis() function instead.
```{r}
?axis
```
```{r}
# Axis-labels and title are straightforward parameters of plot
plot(x,y, xlab="rnorm(n)",
ylab="x^3 * 0.25 + rnorm(n, sd=0.75)",
cex.main=1.3,
main="Sample\nPlot",
cex.sub=0.75,
col.sub="grey",
sub="Scatterplot of noisy 3d-degree polynomial"
)
```
Add gridlines
```{r}
?grid
plot(x,y, xlab="rnorm(n)",
ylab="x^3 * 0.25 + rnorm(n, sd=0.75)",
cex.main=1.3,
main="Sample\nPlot",
cex.sub=0.75,
col.sub="grey",
sub="Scatterplot of noisy 3d-degree polynomial"
)
grid()
```
## Layout
### par, lattice, constant aspect ratio
Most parameters of the plot window can be set via the functions plot(), hist() etc., but some need to be set via the par() function. Calling par() without arguments lists the current state of the plotting parameters. Calling it with arguments, returns the old parameters and sets new parameters. Thus setting new parameters and saving the old ones can be done in one step. The parameters that have to be set via
par include:
* multiple plots in one window (mfrow, mfcol, mfg)
* margin layout (mai, mar mex, oma, omd, omi)
* controlling position and size of a plot in the figure (fig, plt, ps, pty)
* see ?par for details.
```{r}
n <- 1000
x <- rnorm(n)
y <- x^3 * 0.25 + rnorm(n, sd=0.75)
```
```{r}
# set window background and plotting axes via par
opar <- par(bg="steelblue", fg="lightyellow")
# set axis lables and titles via plot parameters
plot(x,y, col.axis="lightyellow", col.lab="lightyellow")
par(opar) # rest to old values
plot(x,y) # confirm reset
```
## Plot symbols and text
Plot symbols are defined in the pch argument to plot(). id 1:20 are regular symbols
```{r}
# Empty plot frame ...
plot(c(0,10), c(0,10), type = "n", axes = FALSE, xlab = "", ylab = "")
# coordinates for first 25 symbols
x1 <- rep(0.5:9.5, 2)[1:20]
y1 <- sort(rep(9.5:8.5, 10), dec=TRUE)[1:20]
points(x1, y1, pch=1:20)
```
```{r}
# Empty plot frame ...
plot(c(0,10), c(0,10), type = "n", axes = FALSE, xlab = "", ylab = "")
# id 21:25 can have different border and fill colours
x2 <- 0.5:4.5
y2 <- rep(7.5,5)
points(x2, y2, pch=21:25, col="slategrey", bg=rainbow(5))
```
```{r}
# Empty plot frame ...
plot(c(0,10), c(0,10), type = "n", axes = FALSE, xlab = "", ylab = "")
# ten extra symbols are defined as characters
x3 <- 0.5:9.5
y3 <- rep(6.5,10)
extra = c(".", "o", "O", "0","a","A", "*", "+","-","|")
points(x3, y3, pch=extra) # note: ext is a character vector
```
```{r}
# Empty plot frame ...
plot(c(0,10), c(0,10), type = "n", axes = FALSE, xlab = "", ylab = "")
# The ASCII codes for characters 32 to 126 can also be used as plotting symbols
x4 <- rep(seq(0.5,9.5,0.5), 5)[1:96]
y4 <- sort(rep(5.5:0.5, 19), dec=TRUE)[1:96]
points(x4, y4, pch=32:126, col="navyblue")
```
Plotting arbitrary text use the text() function to plot characters and strings to coordinates
```{r}
?text
```
```{r}
# Empty plot frame ...
plot(c(0,10), c(0,10), type = "n", axes = FALSE, xlab = "", ylab = "")
# Example: add labels to the symbols
# first set: plain symbols (1 to 20)
text(x1-0.4, y1, paste(1:20), cex=0.75)
# symbols with separate background (21 to 25)
text(x2-0.4, y2, paste(21:25), cex=0.75)
# third set: special characters, change font for clarity
text(x3-0.4, y3, extra, col="slateblue", cex=0.75, vfont=c("serif", "plain"))
```
a large set of Hershey vector fonts is available which gives access to many more plotting and labeling options via text()
```{r}
demo(Hershey)
```
Plotting other symbols:
In the most general way, Unicode characters can be plotted as text. The code is passed in hexadecimal, long integer, with a negative sign. Here is a quarter note (Unicode: 266a) using plot()
```{r}
plot(0.5,0.5, pch=-0x266aL, cex=5, xlab="", ylab="")
```
However, rendering varies across platforms since it depends on unicode support. It is safer to use the inbuilt Hershey vector fonts.
## Drawing on plots
* abline()
* segments()
* lines()
* arrows() ... but to get a filled arrow use polygon()
Example: dividing a plot into 60° regions, centred on a point. A general approach to "lines" on a plot is provided by segments(). However in this special case one can use abline(). We have to take care though that the aspect ratio for the plot is exactly 1 - otherwise our angles are not right. Therefore we need to set the asp parameter for plots.
For a general sketch
* we plot the frame a bit larger, don't draw axes
* draw the ablines
* draw two arrows to symbolize the coordinate axes
```{r}
p <- c(4, 2)
plot(p[1], p[2],
xlim=c(-0.5,10.5),
ylim=c(-0.5,10.5),
xlab="", ylab="",
axes=FALSE,
asp=1.0)
abline(h=p[2], lty=2) # horizontal
abline(p[2] - (p[1]*tan(pi/3)), tan(pi/3), lty=2) # intercept, slope
abline(p[2] + (p[1]*tan(pi/3)), -tan(pi/3), lty=2) # intercept, slope
arrows(0, 0, 10, 0, length=0.1) # length of arrow
arrows(0, 0, 0, 10, length=0.1)
```
* curves()
* rect()
* polygon()
* More: see the Index of functions for the graphics package
## Special packages
Packages in the standard distribution:
* use with library("package")
* graphics
* grid
* lattice
Packages that can be downloaded from CRAN:
* use with install.packages("package"), then library("package")
* hexbin
* ggplot2
Packages that can be downloaded from BioConductor
* prada:
```{r}
if (!requireNamespace("prada", quietly = TRUE)){
#install.packages("BiocManager")
BiocManager::install("prada",ask = FALSE,
force=TRUE)
}
```
Try:
```{r}
n <- 1000
x <- rnorm(n)
y <- x^3 * 0.25 + rnorm(n, sd=0.75)
# smoothed scatterplot with outliers
smoothScatter(x,y, nrpoints=200, pch=20, cex=0.5, col="#6633BB55")
```
```{r}
# density adapted colours
plot (x, y, col=densCols(x,y), pch=19, cex=1.5)
```
## Self-evaluation
## Further reading, links and resources
**If in doubt, ask!**<br>
If anything about this learning unit is not clear to you, do not proceed blindly but ask for clarification. Post your question on the course mailing list: others are likely to have similar problems. Or send an email to your instructor.
```{block2, type="rmd-original-history"}
<br>**Author**: Boris Steipe <[email protected]> <br>
**Created**: 2017-08-05<br>
**Modified**: 2018-05-05<br>
Version: 1.0.1<br>
**Version history**:<br>
1.0.1 Maintenance<br>
1.0 Completed to first live version<br>
0.1 Material collected from previous tutorial<br>
```
### Updated Revision history
```{r echo=FALSE}
source("./bcb420_books_helper_functions.R")
knitr::kable(githistory2table(git2r::commits(repo=".",path=knitr::current_input())))
```
### Footnotes: