The R Project SVN R

Rev

Rev 62864 | Rev 63381 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
56353 ripley 1
 
63202 ripley 2
R Under development (unstable) (2013-07-06 r63201) -- "Unsuffered Consequences"
61587 ripley 3
Copyright (C) 2013 The R Foundation for Statistical Computing
61435 ripley 4
Platform: x86_64-unknown-linux-gnu (64-bit)
56353 ripley 5
 
6
R is free software and comes with ABSOLUTELY NO WARRANTY.
7
You are welcome to redistribute it under certain conditions.
8
Type 'license()' or 'licence()' for distribution details.
9
 
10
  Natural language support but running in an English locale
11
 
12
R is a collaborative project with many contributors.
13
Type 'contributors()' for more information and
14
'citation()' on how to cite R or R packages in publications.
15
 
16
Type 'demo()' for some demos, 'help()' for on-line help, or
17
'help.start()' for an HTML browser interface to help.
18
Type 'q()' to quit R.
19
 
20
> pkgname <- "graphics"
21
> source(file.path(R.home("share"), "R", "examples-header.R"))
22
> options(warn = 1)
23
> library('graphics')
24
> 
61787 ripley 25
> base::assign(".oldSearch", base::search(), pos = 'CheckExEnv')
56353 ripley 26
> cleanEx()
27
> nameEx("abline")
28
> ### * abline
29
> 
30
> flush(stderr()); flush(stdout())
31
> 
32
> ### Name: abline
33
> ### Title: Add Straight Lines to a Plot
34
> ### Aliases: abline
35
> ### Keywords: aplot
36
> 
37
> ### ** Examples
38
> 
61157 ripley 39
> ## Setup up coordinate system (with x == y aspect ratio):
40
> plot(c(-2,3), c(-1,5), type = "n", xlab = "x", ylab = "y", asp = 1)
56353 ripley 41
> ## the x- and y-axis, and an integer grid
61157 ripley 42
> abline(h = 0, v = 0, col = "gray60")
56353 ripley 43
> text(1,0, "abline( h = 0 )", col = "gray60", adj = c(0, -.1))
61157 ripley 44
> abline(h = -1:5, v = -2:3, col = "lightgray", lty = 3)
45
> abline(a = 1, b = 2, col = 2)
61169 ripley 46
> text(1,3, "abline( 1, 2 )", col = 2, adj = c(-.1, -.1))
56353 ripley 47
> 
48
> ## Simple Regression Lines:
49
> require(stats)
50
> sale5 <- c(6, 4, 9, 7, 6, 12, 8, 10, 9, 13)
51
> plot(sale5)
61169 ripley 52
> abline(lsfit(1:10, sale5))
53
> abline(lsfit(1:10, sale5, intercept = FALSE), col = 4) # less fitting
56353 ripley 54
> 
55
> z <- lm(dist ~ speed, data = cars)
56
> plot(cars)
57
> abline(z) # equivalent to abline(reg = z) or
58
> abline(coef = coef(z))
59
> 
60
> ## trivial intercept model
61
> abline(mC <- lm(dist ~ 1, data = cars)) ## the same as
62
> abline(a = coef(mC), b = 0, col = "blue")
63
> 
64
> 
65
> 
66
> cleanEx()
67
> nameEx("arrows")
68
> ### * arrows
69
> 
70
> flush(stderr()); flush(stdout())
71
> 
72
> ### Name: arrows
73
> ### Title: Add Arrows to a Plot
74
> ### Aliases: arrows
75
> ### Keywords: aplot
76
> 
77
> ### ** Examples
78
> 
79
> x <- stats::runif(12); y <- stats::rnorm(12)
61169 ripley 80
> i <- order(x, y); x <- x[i]; y <- y[i]
61157 ripley 81
> plot(x,y, main = "arrows(.) and segments(.)")
56353 ripley 82
> ## draw arrows from point to point :
61169 ripley 83
> s <- seq(length(x)-1)  # one shorter than data
61157 ripley 84
> arrows(x[s], y[s], x[s+1], y[s+1], col = 1:3)
56353 ripley 85
> s <- s[-length(s)]
61169 ripley 86
> segments(x[s], y[s], x[s+2], y[s+2], col = "pink")
56353 ripley 87
> 
88
> 
89
> 
90
> cleanEx()
91
> nameEx("assocplot")
92
> ### * assocplot
93
> 
94
> flush(stderr()); flush(stdout())
95
> 
96
> ### Name: assocplot
97
> ### Title: Association Plots
98
> ### Aliases: assocplot
99
> ### Keywords: hplot
100
> 
101
> ### ** Examples
102
> 
103
> ## Aggregate over sex:
104
> x <- margin.table(HairEyeColor, c(1, 2))
105
> x
106
       Eye
107
Hair    Brown Blue Hazel Green
108
  Black    68   20    15     5
109
  Brown   119   84    54    29
110
  Red      26   17    14    14
111
  Blond     7   94    10    16
112
> assocplot(x, main = "Relation between hair and eye color")
113
> 
114
> 
115
> 
116
> cleanEx()
117
> nameEx("axTicks")
118
> ### * axTicks
119
> 
120
> flush(stderr()); flush(stdout())
121
> 
122
> ### Name: axTicks
123
> ### Title: Compute Axis Tickmark Locations
124
> ### Aliases: axTicks
125
> ### Keywords: dplot
126
> 
127
> ### ** Examples
128
> 
129
>  plot(1:7, 10*21:27)
130
>  axTicks(1)
131
[1] 1 2 3 4 5 6 7
132
>  axTicks(2)
133
[1] 210 220 230 240 250 260 270
134
>  stopifnot(identical(axTicks(1), axTicks(3)),
135
+            identical(axTicks(2), axTicks(4)))
136
> 
137
> ## Show how axTicks() and axis() correspond :
61169 ripley 138
> op <- par(mfrow = c(3, 1))
139
> for(x in 9999 * c(1, 2, 8)) {
140
+     plot(x, 9, log = "x")
61157 ripley 141
+     cat(formatC(par("xaxp"), width = 5),";", T <- axTicks(1),"\n")
142
+     rug(T, col =  adjustcolor("red", 0.5), lwd = 4)
56353 ripley 143
+ }
144
 1000 1e+05     3 ; 200 500 1000 2000 5000 10000 20000 50000 1e+05 2e+05 5e+05 
145
 1000 1e+06     2 ; 500 1000 5000 10000 50000 1e+05 5e+05 1e+06 
146
 1000 1e+07     1 ; 1000 10000 1e+05 1e+06 1e+07 
147
> par(op)
148
> 
57122 maechler 149
> x <- 9.9*10^(-3:10)
150
> plot(x, 1:14, log = "x")
151
> axTicks(1) # now length 5, in R <= 2.13.x gave the following
152
[1] 1e-02 1e+01 1e+04 1e+07 1e+10
61157 ripley 153
> axTicks(1, nintLog = Inf) # rather too many
57122 maechler 154
 [1] 1e-02 1e-01 1e+00 1e+01 1e+02 1e+03 1e+04 1e+05 1e+06 1e+07 1e+08 1e+09
155
[13] 1e+10 1e+11
156
> 
56353 ripley 157
> ## An example using axTicks() without reference to an existing plot
158
> ## (copying R's internal procedures for setting axis ranges etc.),
57360 ripley 159
> ## You do need to supply _all_ of axp, usr, log, nintLog
56353 ripley 160
> ## standard logarithmic y axis labels
161
> ylims <- c(0.2, 88)
162
> get_axp <- function(x) 10^c(ceiling(x[1]), floor(x[2]))
61157 ripley 163
> ## mimic par("yaxs") == "i"
56353 ripley 164
> usr.i <- log10(ylims)
61157 ripley 165
> (aT.i <- axTicks(side = 2, usr = usr.i,
166
+                  axp = c(get_axp(usr.i), n = 3), log = TRUE, nintLog = 5))
57362 ripley 167
[1]  0.2  0.5  1.0  2.0  5.0 10.0 20.0 50.0
61157 ripley 168
> ## mimic (default) par("yaxs") == "r"
56353 ripley 169
> usr.r <- extendrange(r = log10(ylims), f = 0.04)
61157 ripley 170
> (aT.r <- axTicks(side = 2, usr = usr.r,
171
+                  axp = c(get_axp(usr.r), 3), log = TRUE, nintLog = 5))
56353 ripley 172
[1]   0.2   0.5   1.0   2.0   5.0  10.0  20.0  50.0 100.0
173
> 
174
> ## Prove that we got it right :
61157 ripley 175
> plot(0:1, ylims, log = "y", yaxs = "i")
176
> stopifnot(all.equal(aT.i, axTicks(side = 2)))
56353 ripley 177
> 
61169 ripley 178
> plot(0:1, ylims, log = "y", yaxs = "r")
61157 ripley 179
> stopifnot(all.equal(aT.r, axTicks(side = 2)))
56353 ripley 180
> 
181
> 
182
> 
183
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
184
> cleanEx()
185
> nameEx("axis.POSIXct")
186
> ### * axis.POSIXct
187
> 
188
> flush(stderr()); flush(stdout())
189
> 
190
> ### Name: axis.POSIXct
191
> ### Title: Date and Date-time Plotting Functions
192
> ### Aliases: axis.POSIXct axis.Date
193
> ### Keywords: utilities chron
194
> 
195
> ### ** Examples
196
> 
197
> with(beaver1, {
198
+ time <- strptime(paste(1990, day, time %/% 100, time %% 100),
199
+                  "%Y %j %H %M")
61157 ripley 200
+ plot(time, temp, type = "l") # axis at 4-hour intervals.
56353 ripley 201
+ # now label every hour on the time axis
61157 ripley 202
+ plot(time, temp, type = "l", xaxt = "n")
56353 ripley 203
+ r <- as.POSIXct(round(range(time), "hours"))
61157 ripley 204
+ axis.POSIXct(1, at = seq(r[1], r[2], by = "hour"), format = "%H")
56353 ripley 205
+ })
206
> 
61157 ripley 207
> plot(.leap.seconds, seq_along(.leap.seconds), type = "n", yaxt = "n",
208
+      xlab = "leap seconds", ylab = "", bty = "n")
56353 ripley 209
> rug(.leap.seconds)
210
> ## or as dates
211
> lps <- as.Date(.leap.seconds)
212
> plot(lps, seq_along(.leap.seconds),
213
+      type = "n", yaxt = "n", xlab = "leap seconds",
214
+      ylab = "", bty = "n")
215
> rug(lps)
216
> 
217
> ## 100 random dates in a 10-week period
218
> random.dates <- as.Date("2001/1/1") + 70*sort(stats::runif(100))
219
> plot(random.dates, 1:100)
220
> # or for a better axis labelling
61157 ripley 221
> plot(random.dates, 1:100, xaxt = "n")
222
> axis.Date(1, at = seq(as.Date("2001/1/1"), max(random.dates)+6, "weeks"))
223
> axis.Date(1, at = seq(as.Date("2001/1/1"), max(random.dates)+6, "days"),
56353 ripley 224
+      labels = FALSE, tcl = -0.2)
225
> 
226
> 
227
> 
228
> cleanEx()
229
> nameEx("axis")
230
> ### * axis
231
> 
232
> flush(stderr()); flush(stdout())
233
> 
234
> ### Name: axis
235
> ### Title: Add an Axis to a Plot
236
> ### Aliases: axis
237
> ### Keywords: aplot
238
> 
239
> ### ** Examples
240
> 
241
> require(stats) # for rnorm
242
> plot(1:4, rnorm(4), axes = FALSE)
243
> axis(1, 1:4, LETTERS[1:4])
244
> axis(2)
245
> box() #- to make it look "as usual"
246
> 
247
> plot(1:7, rnorm(7), main = "axis() examples",
248
+      type = "s", xaxt = "n", frame = FALSE, col = "red")
249
> axis(1, 1:7, LETTERS[1:7], col.axis = "blue")
250
> # unusual options:
61157 ripley 251
> axis(4, col = "violet", col.axis = "dark violet", lwd = 2)
56353 ripley 252
> axis(3, col = "gold", lty = 2, lwd = 0.5)
253
> 
254
> # one way to have a custom x axis
255
> plot(1:10, xaxt = "n")
61157 ripley 256
> axis(1, xaxp = c(2, 9, 7))
56353 ripley 257
> 
258
> 
259
> 
260
> cleanEx()
261
> nameEx("barplot")
262
> ### * barplot
263
> 
264
> flush(stderr()); flush(stdout())
265
> 
266
> ### Name: barplot
267
> ### Title: Bar Plots
268
> ### Aliases: barplot barplot.default
269
> ### Keywords: hplot
270
> 
271
> ### ** Examples
272
> 
273
> require(grDevices) # for colours
61157 ripley 274
> tN <- table(Ni <- stats::rpois(100, lambda = 5))
275
> r <- barplot(tN, col = rainbow(20))
56353 ripley 276
> #- type = "h" plotting *is* 'bar'plot
61169 ripley 277
> lines(r, tN, type = "h", col = "red", lwd = 2)
56353 ripley 278
> 
61157 ripley 279
> barplot(tN, space = 1.5, axisnames = FALSE,
56353 ripley 280
+         sub = "barplot(..., space= 1.5, axisnames = FALSE)")
281
> 
282
> barplot(VADeaths, plot = FALSE)
283
[1] 0.7 1.9 3.1 4.3
284
> barplot(VADeaths, plot = FALSE, beside = TRUE)
285
     [,1] [,2] [,3] [,4]
286
[1,]  1.5  7.5 13.5 19.5
287
[2,]  2.5  8.5 14.5 20.5
288
[3,]  3.5  9.5 15.5 21.5
289
[4,]  4.5 10.5 16.5 22.5
290
[5,]  5.5 11.5 17.5 23.5
291
> 
292
> mp <- barplot(VADeaths) # default
293
> tot <- colMeans(VADeaths)
294
> text(mp, tot + 3, format(tot), xpd = TRUE, col = "blue")
295
> barplot(VADeaths, beside = TRUE,
296
+         col = c("lightblue", "mistyrose", "lightcyan",
297
+                 "lavender", "cornsilk"),
298
+         legend = rownames(VADeaths), ylim = c(0, 100))
299
> title(main = "Death Rates in Virginia", font.main = 4)
300
> 
301
> hh <- t(VADeaths)[, 5:1]
302
> mybarcol <- "gray20"
303
> mp <- barplot(hh, beside = TRUE,
304
+         col = c("lightblue", "mistyrose",
305
+                 "lightcyan", "lavender"),
61157 ripley 306
+         legend = colnames(VADeaths), ylim = c(0,100),
56353 ripley 307
+         main = "Death Rates in Virginia", font.main = 4,
308
+         sub = "Faked upper 2*sigma error bars", col.sub = mybarcol,
309
+         cex.names = 1.5)
310
> segments(mp, hh, mp, hh + 2*sqrt(1000*hh/100), col = mybarcol, lwd = 1.5)
61169 ripley 311
> stopifnot(dim(mp) == dim(hh))  # corresponding matrices
56353 ripley 312
> mtext(side = 1, at = colMeans(mp), line = -2,
313
+       text = paste("Mean", formatC(colMeans(hh))), col = "red")
314
> 
315
> # Bar shading example
316
> barplot(VADeaths, angle = 15+10*1:5, density = 20, col = "black",
317
+         legend = rownames(VADeaths))
318
> title(main = list("Death Rates in Virginia", font = 4))
319
> 
320
> # border :
321
> barplot(VADeaths, border = "dark blue") 
322
> 
323
> # log scales (not much sense here):
61157 ripley 324
> barplot(tN, col = heat.colors(12), log = "y")
325
> barplot(tN, col = gray.colors(20), log = "xy")
56353 ripley 326
> 
327
> # args.legend
328
> barplot(height = cbind(x = c(465, 91) / 465 * 100,
329
+                        y = c(840, 200) / 840 * 100,
330
+                        z = c(37, 17) / 37 * 100),
331
+         beside = FALSE,
332
+         width = c(465, 840, 37),
333
+         col = c(1, 2),
334
+         legend.text = c("A", "B"),
335
+         args.legend = list(x = "topleft"))
336
> 
337
> 
338
> 
339
> cleanEx()
340
> nameEx("box")
341
> ### * box
342
> 
343
> flush(stderr()); flush(stdout())
344
> 
345
> ### Name: box
346
> ### Title: Draw a Box around a Plot
347
> ### Aliases: box
348
> ### Keywords: aplot
349
> 
350
> ### ** Examples
351
> 
61169 ripley 352
> plot(1:7, abs(stats::rnorm(7)), type = "h", axes = FALSE)
56353 ripley 353
> axis(1, at = 1:7, labels = letters[1:7])
354
> box(lty = '1373', col = 'red')
355
> 
356
> 
357
> 
358
> cleanEx()
359
> nameEx("boxplot")
360
> ### * boxplot
361
> 
362
> flush(stderr()); flush(stdout())
363
> 
364
> ### Name: boxplot
365
> ### Title: Box Plots
366
> ### Aliases: boxplot boxplot.default boxplot.formula
367
> ### Keywords: hplot
368
> 
369
> ### ** Examples
370
> 
371
> ## boxplot on a formula:
372
> boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
373
> # *add* notches (somewhat funny here):
374
> boxplot(count ~ spray, data = InsectSprays,
375
+         notch = TRUE, add = TRUE, col = "blue")
376
Warning in bxp(list(stats = c(7, 11, 14, 18.5, 23, 7, 12, 16.5, 18, 21,  :
377
  some notches went outside hinges ('box'): maybe set notch=FALSE
378
> 
379
> boxplot(decrease ~ treatment, data = OrchardSprays,
380
+         log = "y", col = "bisque")
381
> 
61157 ripley 382
> rb <- boxplot(decrease ~ treatment, data = OrchardSprays, col = "bisque")
56353 ripley 383
> title("Comparing boxplot()s and non-robust mean +/- SD")
384
> 
385
> mn.t <- tapply(OrchardSprays$decrease, OrchardSprays$treatment, mean)
386
> sd.t <- tapply(OrchardSprays$decrease, OrchardSprays$treatment, sd)
387
> xi <- 0.3 + seq(rb$n)
388
> points(xi, mn.t, col = "orange", pch = 18)
389
> arrows(xi, mn.t - sd.t, xi, mn.t + sd.t,
390
+        code = 3, col = "pink", angle = 75, length = .1)
391
> 
392
> ## boxplot on a matrix:
393
> mat <- cbind(Uni05 = (1:100)/21, Norm = rnorm(100),
394
+              `5T` = rt(100, df = 5), Gam2 = rgamma(100, shape = 2))
395
> boxplot(as.data.frame(mat),
396
+         main = "boxplot(as.data.frame(mat), main = ...)")
61157 ripley 397
> par(las = 1) # all axis labels horizontal
56353 ripley 398
> boxplot(as.data.frame(mat), main = "boxplot(*, horizontal = TRUE)",
399
+         horizontal = TRUE)
400
> 
401
> ## Using 'at = ' and adding boxplots -- example idea by Roger Bivand :
402
> 
403
> boxplot(len ~ dose, data = ToothGrowth,
404
+         boxwex = 0.25, at = 1:3 - 0.2,
405
+         subset = supp == "VC", col = "yellow",
406
+         main = "Guinea Pigs' Tooth Growth",
407
+         xlab = "Vitamin C dose mg",
408
+         ylab = "tooth length",
409
+         xlim = c(0.5, 3.5), ylim = c(0, 35), yaxs = "i")
410
> boxplot(len ~ dose, data = ToothGrowth, add = TRUE,
411
+         boxwex = 0.25, at = 1:3 + 0.2,
412
+         subset = supp == "OJ", col = "orange")
413
> legend(2, 9, c("Ascorbic acid", "Orange juice"),
414
+        fill = c("yellow", "orange"))
415
> 
416
> ## more examples in  help(bxp)
417
> 
418
> 
419
> 
420
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
421
> cleanEx()
422
> nameEx("boxplot.matrix")
423
> ### * boxplot.matrix
424
> 
425
> flush(stderr()); flush(stdout())
426
> 
427
> ### Name: boxplot.matrix
428
> ### Title: Draw a Boxplot for each Column (Row) of a Matrix
429
> ### Aliases: boxplot.matrix
430
> ### Keywords: hplot
431
> 
432
> ### ** Examples
433
> 
434
> ## Very similar to the example in ?boxplot
435
> mat <- cbind(Uni05 = (1:100)/21, Norm = rnorm(100),
436
+              T5 = rt(100, df = 5), Gam2 = rgamma(100, shape = 2))
437
> boxplot(mat, main = "boxplot.matrix(...., main = ...)",
438
+         notch = TRUE, col = 1:4)
439
> 
440
> 
441
> 
442
> cleanEx()
443
> nameEx("bxp")
444
> ### * bxp
445
> 
446
> flush(stderr()); flush(stdout())
447
> 
448
> ### Name: bxp
449
> ### Title: Draw Box Plots from Summaries
450
> ### Aliases: bxp
451
> ### Keywords: aplot
452
> 
453
> ### ** Examples
454
> 
455
> require(stats)
456
> set.seed(753)
61169 ripley 457
> (bx.p <- boxplot(split(rt(100, 4), gl(5, 20))))
56353 ripley 458
$stats
459
            [,1]        [,2]        [,3]        [,4]        [,5]
460
[1,] -1.66391873 -2.02625162 -2.12785004 -2.76510496 -1.70034047
461
[2,] -0.55308292 -0.65897584 -0.86705616 -1.63431484 -0.81848966
462
[3,] -0.06763313  0.04887846  0.09674026 -0.06712275 -0.01150075
463
[4,]  0.68813940  0.91705734  1.05562526  0.56746581  0.49017934
464
[5,]  1.14222667  3.16270157  2.07574986  2.09523462  1.87734641
465
 
466
$n
467
[1] 20 20 20 20 20
468
 
469
$conf
470
           [,1]       [,2]       [,3]       [,4]       [,5]
471
[1,] -0.5061554 -0.5079321 -0.5825407 -0.8450091 -0.4738519
472
[2,]  0.3708891  0.6056890  0.7760212  0.7107636  0.4508504
473
 
474
$out
475
[1]  4.115274  3.224584  3.920438  4.168341 -4.357819  2.498006
476
 
477
$group
478
[1] 1 1 1 4 5 5
479
 
480
$names
481
[1] "1" "2" "3" "4" "5"
482
 
61169 ripley 483
> op <- par(mfrow =  c(2, 2))
56353 ripley 484
> bxp(bx.p, xaxt = "n")
61157 ripley 485
> bxp(bx.p, notch = TRUE, axes = FALSE, pch = 4, boxfill = 1:5)
56353 ripley 486
Warning in bxp(bx.p, notch = TRUE, axes = FALSE, pch = 4, boxfill = 1:5) :
487
  some notches went outside hinges ('box'): maybe set notch=FALSE
61157 ripley 488
> bxp(bx.p, notch = TRUE, boxfill = "lightblue", frame = FALSE,
489
+     outl = FALSE, main = "bxp(*, frame= FALSE, outl= FALSE)")
56353 ripley 490
Warning in bxp(bx.p, notch = TRUE, boxfill = "lightblue", frame = FALSE,  :
491
  some notches went outside hinges ('box'): maybe set notch=FALSE
61157 ripley 492
> bxp(bx.p, notch = TRUE, boxfill = "lightblue", border = 2:6,
56353 ripley 493
+     ylim = c(-4,4), pch = 22, bg = "green", log = "x",
61169 ripley 494
+     main = "... log = 'x', ylim = *")
56353 ripley 495
Warning in bxp(bx.p, notch = TRUE, boxfill = "lightblue", border = 2:6,  :
496
  some notches went outside hinges ('box'): maybe set notch=FALSE
497
> par(op)
61169 ripley 498
> op <- par(mfrow = c(1, 2))
56353 ripley 499
> 
500
> ## single group -- no label
61157 ripley 501
> boxplot (weight ~ group, data = PlantGrowth, subset = group == "ctrl")
56353 ripley 502
> ## with label
503
> bx <- boxplot(weight ~ group, data = PlantGrowth,
61157 ripley 504
+               subset = group == "ctrl", plot = FALSE)
61169 ripley 505
> bxp(bx, show.names=TRUE)
56353 ripley 506
> par(op)
507
> 
61157 ripley 508
> z <- split(rnorm(1000), rpois(1000, 2.2))
509
> boxplot(z, whisklty = 3, main = "boxplot(z, whisklty = 3)")
56353 ripley 510
> 
511
> ## Colour support similar to plot.default:
61157 ripley 512
> op <- par(mfrow = 1:2, bg = "light gray", fg = "midnight blue")
513
> boxplot(z,   col.axis = "skyblue3", main = "boxplot(*, col.axis=..,main=..)")
514
> plot(z[[1]], col.axis = "skyblue3", main =    "plot(*, col.axis=..,main=..)")
56353 ripley 515
> mtext("par(bg=\"light gray\", fg=\"midnight blue\")",
516
+       outer = TRUE, line = -1.2)
517
> par(op)
518
> 
519
> ## Mimic S-Plus:
61157 ripley 520
> splus <- list(boxwex = 0.4, staplewex = 1, outwex = 1, boxfill = "grey40",
521
+               medlwd = 3, medcol = "white", whisklty = 3, outlty = 1, outpch = NA)
522
> boxplot(z, pars = splus)
56353 ripley 523
> ## Recycled and "sweeping" parameters
61157 ripley 524
> op <- par(mfrow = c(1,2))
525
>  boxplot(z, border = 1:5, lty = 3, medlty = 1, medlwd = 2.5)
526
>  boxplot(z, boxfill = 1:3, pch = 1:5, lwd = 1.5, medcol = "white")
56353 ripley 527
> par(op)
528
> ## too many possibilities
61157 ripley 529
> boxplot(z, boxfill = "light gray", outpch = 21:25, outlty = 2,
56353 ripley 530
+         bg = "pink", lwd = 2,
531
+         medcol = "dark blue", medcex = 2, medpch = 20)
532
> 
533
> 
534
> 
535
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
536
> cleanEx()
537
> nameEx("cdplot")
538
> ### * cdplot
539
> 
540
> flush(stderr()); flush(stdout())
541
> 
542
> ### Name: cdplot
543
> ### Title: Conditional Density Plots
544
> ### Aliases: cdplot cdplot.default cdplot.formula
545
> ### Keywords: hplot
546
> 
547
> ### ** Examples
548
> 
549
> ## NASA space shuttle o-ring failures
550
> fail <- factor(c(2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1,
551
+                  1, 2, 1, 1, 1, 1, 1),
552
+                levels = 1:2, labels = c("no", "yes"))
553
> temperature <- c(53, 57, 58, 63, 66, 67, 67, 67, 68, 69, 70, 70,
554
+                  70, 70, 72, 73, 75, 75, 76, 76, 78, 79, 81)
555
> 
556
> ## CD plot
557
> cdplot(fail ~ temperature)
558
> cdplot(fail ~ temperature, bw = 2)
559
> cdplot(fail ~ temperature, bw = "SJ")
560
> 
561
> ## compare with spinogram
562
> (spineplot(fail ~ temperature, breaks = 3))
563
           fail
564
temperature no yes
565
    [50,60]  0   3
566
    (60,70]  8   3
567
    (70,80]  7   1
568
    (80,90]  1   0
569
> 
570
> ## highlighting for failures
571
> cdplot(fail ~ temperature, ylevels = 2:1)
572
> 
573
> ## scatter plot with conditional density
574
> cdens <- cdplot(fail ~ temperature, plot = FALSE)
575
> plot(I(as.numeric(fail) - 1) ~ jitter(temperature, factor = 2),
576
+      xlab = "Temperature", ylab = "Conditional failure probability")
577
> lines(53:81, 1 - cdens[[1]](53:81), col = 2)
578
> 
579
> 
580
> 
581
> cleanEx()
582
> nameEx("clip")
583
> ### * clip
584
> 
585
> flush(stderr()); flush(stdout())
586
> 
587
> ### Name: clip
588
> ### Title: Set Clipping Region
589
> ### Aliases: clip
590
> ### Keywords: dplot
591
> 
592
> ### ** Examples
593
> 
594
> x <- rnorm(1000)
61157 ripley 595
> hist(x, xlim = c(-4,4))
56353 ripley 596
> usr <- par("usr")
597
> clip(usr[1], -2, usr[3], usr[4])
598
> hist(x, col = 'red', add = TRUE)
599
> clip(2, usr[2], usr[3], usr[4])
600
> hist(x, col = 'blue', add = TRUE)
601
> do.call("clip", as.list(usr))  # reset to plot region
602
> 
603
> 
604
> 
605
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
606
> cleanEx()
607
> nameEx("contour")
608
> ### * contour
609
> 
610
> flush(stderr()); flush(stdout())
611
> 
612
> ### Name: contour
613
> ### Title: Display Contours
614
> ### Aliases: contour contour.default
615
> ### Keywords: hplot aplot
616
> 
617
> ### ** Examples
618
> 
619
> require(grDevices) # for colours
620
> x <- -6:16
621
> op <- par(mfrow = c(2, 2))
622
> contour(outer(x, x), method = "edge", vfont = c("sans serif", "plain"))
623
> z <- outer(x, sqrt(abs(x)), FUN = "/")
624
> image(x, x, z)
625
> contour(x, x, z, col = "pink", add = TRUE, method = "edge",
626
+         vfont = c("sans serif", "plain"))
627
> contour(x, x, z, ylim = c(1, 6), method = "simple", labcex = 1)
628
> contour(x, x, z, ylim = c(-6, 6), nlev = 20, lty = 2, method = "simple")
629
> par(op)
630
> 
631
> ## Persian Rug Art:
632
> x <- y <- seq(-4*pi, 4*pi, len = 27)
633
> r <- sqrt(outer(x^2, y^2, "+"))
634
> opar <- par(mfrow = c(2, 2), mar = rep(0, 4))
635
> for(f in pi^(0:3))
636
+   contour(cos(r^2)*exp(-r/f),
637
+           drawlabels = FALSE, axes = FALSE, frame = TRUE)
638
> 
639
> rx <- range(x <- 10*1:nrow(volcano))
640
> ry <- range(y <- 10*1:ncol(volcano))
61169 ripley 641
> ry <- ry + c(-1, 1) * (diff(rx) - diff(ry))/2
56353 ripley 642
> tcol <- terrain.colors(12)
643
> par(opar); opar <- par(pty = "s", bg = "lightcyan")
61169 ripley 644
> plot(x = 0, y = 0, type = "n", xlim = rx, ylim = ry, xlab = "", ylab = "")
56353 ripley 645
> u <- par("usr")
646
> rect(u[1], u[3], u[2], u[4], col = tcol[8], border = "red")
647
> contour(x, y, volcano, col = tcol[2], lty = "solid", add = TRUE,
648
+         vfont = c("sans serif", "plain"))
649
> title("A Topographic Map of Maunga Whau", font = 4)
650
> abline(h = 200*0:4, v = 200*0:4, col = "lightgray", lty = 2, lwd = 0.1)
651
> 
652
> ## contourLines produces the same contour lines as contour
653
> line.list <- contourLines(x, y, volcano)
61169 ripley 654
> plot(x = 0, y = 0, type = "n", xlim = rx, ylim = ry, xlab = "", ylab = "")
56353 ripley 655
> u <- par("usr")
656
> rect(u[1], u[3], u[2], u[4], col = tcol[8], border = "red")
657
> contour(x, y, volcano, col = tcol[2], lty = "solid", add = TRUE,
658
+              vfont = c("sans serif", "plain"))
659
> templines <- function(clines) {
660
+   lines(clines[[2]], clines[[3]])
661
+ }
662
> invisible(lapply(line.list, templines))
663
> par(opar)
664
> 
665
> 
666
> 
667
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
668
> cleanEx()
669
> nameEx("convertXY")
670
> ### * convertXY
671
> 
672
> flush(stderr()); flush(stdout())
673
> 
674
> ### Name: convertXY
675
> ### Title: Convert between Graphics Coordinate Systems
676
> ### Aliases: grconvertX grconvertY
677
> ### Keywords: dplot
678
> 
679
> ### ** Examples
680
> 
681
> op <- par(omd=c(0.1, 0.9, 0.1, 0.9), mfrow = c(1, 2))
682
> plot(1:4)
683
> for(tp in c("in", "dev", "ndc", "nfc", "npc", "nic"))
684
+     print(grconvertX(c(1.0, 4.0), "user", tp))
685
[1] 1.577778 3.022222
56942 ripley 686
[1] 113.6 217.6
56353 ripley 687
[1] 0.2253968 0.4317460
688
[1] 0.3134921 0.8293651
689
[1] 0.03703704 0.96296296
690
[1] 0.1567460 0.4146825
691
> par(op)
692
> 
693
> 
694
> 
695
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
696
> cleanEx()
697
> nameEx("coplot")
698
> ### * coplot
699
> 
700
> flush(stderr()); flush(stdout())
701
> 
702
> ### Name: coplot
703
> ### Title: Conditioning Plots
704
> ### Aliases: coplot co.intervals
705
> ### Keywords: hplot aplot
706
> 
707
> ### ** Examples
708
> 
709
> ## Tonga Trench Earthquakes
710
> coplot(lat ~ long | depth, data = quakes)
61157 ripley 711
> given.depth <- co.intervals(quakes$depth, number = 4, overlap = .1)
712
> coplot(lat ~ long | depth, data = quakes, given.v = given.depth, rows = 1)
56353 ripley 713
> 
714
> ## Conditioning on 2 variables:
715
> ll.dm <- lat ~ long | depth * mag
716
> coplot(ll.dm, data = quakes)
61169 ripley 717
> coplot(ll.dm, data = quakes, number = c(4, 7), show.given = c(TRUE, FALSE))
718
> coplot(ll.dm, data = quakes, number = c(3, 7),
719
+        overlap = c(-.5, .1)) # negative overlap DROPS values
56353 ripley 720
> 
721
> ## given two factors
61157 ripley 722
> Index <- seq(length = nrow(warpbreaks)) # to get nicer default labels
56353 ripley 723
> coplot(breaks ~ Index | wool * tension, data = warpbreaks,
724
+        show.given = 0:1)
725
> coplot(breaks ~ Index | wool * tension, data = warpbreaks,
726
+        col = "red", bg = "pink", pch = 21,
727
+        bar.bg = c(fac = "light blue"))
728
> 
729
> ## Example with empty panels:
730
> with(data.frame(state.x77), {
731
+ coplot(Life.Exp ~ Income | Illiteracy * state.region, number = 3,
732
+        panel = function(x, y, ...) panel.smooth(x, y, span = .8, ...))
733
+ ## y ~ factor -- not really sensible, but 'show off':
734
+ coplot(Life.Exp ~ state.region | Income * state.division,
735
+        panel = panel.smooth)
736
+ })
737
> 
738
> 
739
> 
740
> cleanEx()
741
> nameEx("curve")
742
> ### * curve
743
> 
744
> flush(stderr()); flush(stdout())
745
> 
746
> ### Name: curve
747
> ### Title: Draw Function Plots
748
> ### Aliases: curve plot.function
749
> ### Keywords: hplot
750
> 
751
> ### ** Examples
752
> 
753
> plot(qnorm) # default range c(0, 1) is appropriate here,
754
>             # but end values are -/+Inf and so are omitted.
755
> plot(qlogis, main = "The Inverse Logit : qlogis()")
756
> abline(h = 0, v = 0:2/2, lty = 3, col = "gray")
757
> 
758
> curve(sin, -2*pi, 2*pi, xname = "t")
759
> curve(tan, xname = "t", add = NA,
760
+       main = "curve(tan)  --> same x-scale as previous plot")
761
> 
762
> op <- par(mfrow = c(2, 2))
763
> curve(x^3 - 3*x, -2, 2)
764
> curve(x^2 - 2, add = TRUE, col = "violet")
765
> 
766
> ## simple and advanced versions, quite similar:
767
> plot(cos, -pi,  3*pi)
768
> curve(cos, xlim = c(-pi, 3*pi), n = 1001, col = "blue", add = TRUE)
769
> 
770
> chippy <- function(x) sin(cos(x)*exp(-x/2))
771
> curve(chippy, -8, 7, n = 2001)
772
> plot (chippy, -8, -5)
773
> 
774
> for(ll in c("", "x", "y", "xy"))
61157 ripley 775
+    curve(log(1+x), 1, 100, log = ll, sub = paste0("log = '", ll, "'"))
56353 ripley 776
> par(op)
777
> 
778
> 
779
> 
780
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
781
> cleanEx()
782
> nameEx("dotchart")
783
> ### * dotchart
784
> 
785
> flush(stderr()); flush(stdout())
786
> 
787
> ### Name: dotchart
788
> ### Title: Cleveland's Dot Plots
789
> ### Aliases: dotchart
790
> ### Keywords: hplot
791
> 
792
> ### ** Examples
793
> 
794
> dotchart(VADeaths, main = "Death Rates in Virginia - 1940")
61169 ripley 795
> op <- par(xaxs = "i")  # 0 -- 100%
56353 ripley 796
> dotchart(t(VADeaths), xlim = c(0,100),
797
+          main = "Death Rates in Virginia - 1940")
798
> par(op)
799
> 
800
> 
801
> 
802
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
803
> cleanEx()
804
> nameEx("filled.contour")
805
> ### * filled.contour
806
> 
807
> flush(stderr()); flush(stdout())
808
> 
809
> ### Name: filled.contour
810
> ### Title: Level (Contour) Plots
58477 ripley 811
> ### Aliases: filled.contour .filled.contour
56353 ripley 812
> ### Keywords: hplot aplot
813
> 
814
> ### ** Examples
815
> 
816
> require(grDevices) # for colours
61169 ripley 817
> filled.contour(volcano, color = terrain.colors, asp = 1) # simple
56353 ripley 818
> 
819
> x <- 10*1:nrow(volcano)
820
> y <- 10*1:ncol(volcano)
821
> filled.contour(x, y, volcano, color = terrain.colors,
822
+     plot.title = title(main = "The Topography of Maunga Whau",
823
+     xlab = "Meters North", ylab = "Meters West"),
824
+     plot.axes = { axis(1, seq(100, 800, by = 100))
825
+                   axis(2, seq(100, 600, by = 100)) },
61157 ripley 826
+     key.title = title(main = "Height\n(meters)"),
61169 ripley 827
+     key.axes = axis(4, seq(90, 190, by = 10)))  # maybe also asp = 1
56353 ripley 828
> mtext(paste("filled.contour(.) from", R.version.string),
829
+       side = 1, line = 4, adj = 1, cex = .66)
830
> 
831
> # Annotating a filled contour plot
832
> a <- expand.grid(1:20, 1:20)
833
> b <- matrix(a[,1] + a[,2], 20)
834
> filled.contour(x = 1:20, y = 1:20, z = b,
61169 ripley 835
+                plot.axes = { axis(1); axis(2); points(10, 10) })
56353 ripley 836
> 
837
> ## Persian Rug Art:
838
> x <- y <- seq(-4*pi, 4*pi, len = 27)
839
> r <- sqrt(outer(x^2, y^2, "+"))
840
> filled.contour(cos(r^2)*exp(-r/(2*pi)), axes = FALSE)
841
> ## rather, the key *should* be labeled:
842
> filled.contour(cos(r^2)*exp(-r/(2*pi)), frame.plot = FALSE,
843
+                plot.axes = {})
844
> 
845
> 
846
> 
847
> cleanEx()
848
> nameEx("fourfoldplot")
849
> ### * fourfoldplot
850
> 
851
> flush(stderr()); flush(stdout())
852
> 
853
> ### Name: fourfoldplot
854
> ### Title: Fourfold Plots
855
> ### Aliases: fourfoldplot
856
> ### Keywords: hplot
857
> 
858
> ### ** Examples
859
> 
860
> ## Use the Berkeley admission data as in Friendly (1995).
861
> x <- aperm(UCBAdmissions, c(2, 1, 3))
862
> dimnames(x)[[2]] <- c("Yes", "No")
863
> names(dimnames(x)) <- c("Sex", "Admit?", "Department")
864
> stats::ftable(x)
865
              Department   A   B   C   D   E   F
866
Sex    Admit?                                   
867
Male   Yes               512 353 120 138  53  22
868
       No                313 207 205 279 138 351
869
Female Yes                89  17 202 131  94  24
870
       No                 19   8 391 244 299 317
871
> 
872
> ## Fourfold display of data aggregated over departments, with
873
> ## frequencies standardized to equate the margins for admission
874
> ## and sex.
875
> ## Figure 1 in Friendly (1994).
876
> fourfoldplot(margin.table(x, c(1, 2)))
877
> 
878
> ## Fourfold display of x, with frequencies in each table
879
> ## standardized to equate the margins for admission and sex.
880
> ## Figure 2 in Friendly (1994).
881
> fourfoldplot(x)
882
> 
883
> ## Fourfold display of x, with frequencies in each table
884
> ## standardized to equate the margins for admission. but not
885
> ## for sex.
886
> ## Figure 3 in Friendly (1994).
887
> fourfoldplot(x, margin = 2)
888
> 
889
> 
890
> 
891
> cleanEx()
892
> nameEx("grid")
893
> ### * grid
894
> 
895
> flush(stderr()); flush(stdout())
896
> 
897
> ### Name: grid
898
> ### Title: Add Grid to a Plot
899
> ### Aliases: grid
900
> ### Keywords: aplot
901
> 
902
> ### ** Examples
903
> 
904
> plot(1:3)
905
> grid(NA, 5, lwd = 2) # grid only in y-direction
906
> 
61169 ripley 907
> ## maybe change the desired number of tick marks:  par(lab = c(mx, my, 7))
56353 ripley 908
> op <- par(mfcol = 1:2)
909
> with(iris,
910
+      {
911
+      plot(Sepal.Length, Sepal.Width, col = as.integer(Species),
912
+           xlim = c(4, 8), ylim = c(2, 4.5), panel.first = grid(),
913
+           main = "with(iris,  plot(...., panel.first = grid(), ..) )")
914
+      plot(Sepal.Length, Sepal.Width, col = as.integer(Species),
61169 ripley 915
+           panel.first = grid(3, lty = 1, lwd = 2),
916
+           main = "... panel.first = grid(3, lty = 1, lwd = 2), ..")
56353 ripley 917
+      }
918
+     )
919
> par(op)
920
> 
921
> 
922
> 
923
> 
924
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
925
> cleanEx()
926
> nameEx("hist.POSIXt")
927
> ### * hist.POSIXt
928
> 
929
> flush(stderr()); flush(stdout())
930
> 
931
> ### Name: hist.POSIXt
932
> ### Title: Histogram of a Date or Date-Time Object
933
> ### Aliases: hist.POSIXt hist.Date
934
> ### Keywords: chron dplot hplot
935
> 
936
> ### ** Examples
937
> 
938
> hist(.leap.seconds, "years", freq = TRUE)
939
> hist(.leap.seconds,
59697 ripley 940
+      seq(ISOdate(1970, 1, 1), ISOdate(2015, 1, 1), "5 years"))
56353 ripley 941
> 
942
> ## 100 random dates in a 10-week period
943
> random.dates <- as.Date("2001/1/1") + 70*stats::runif(100)
944
> hist(random.dates, "weeks", format = "%d %b")
945
> 
946
> 
947
> 
948
> cleanEx()
949
> nameEx("hist")
950
> ### * hist
951
> 
952
> flush(stderr()); flush(stdout())
953
> 
954
> ### Name: hist
955
> ### Title: Histograms
956
> ### Aliases: hist hist.default
957
> ### Keywords: dplot hplot distribution
958
> 
959
> ### ** Examples
960
> 
61157 ripley 961
> op <- par(mfrow = c(2, 2))
56353 ripley 962
> hist(islands)
61157 ripley 963
> utils::str(hist(islands, col = "gray", labels = TRUE))
61587 ripley 964
List of 6
965
 $ breaks  : num [1:10] 0 2000 4000 6000 8000 10000 12000 14000 16000 18000
966
 $ counts  : int [1:9] 41 2 1 1 1 1 0 0 1
967
 $ density : num [1:9] 4.27e-04 2.08e-05 1.04e-05 1.04e-05 1.04e-05 ...
968
 $ mids    : num [1:9] 1000 3000 5000 7000 9000 11000 13000 15000 17000
969
 $ xname   : chr "islands"
970
 $ equidist: logi TRUE
56353 ripley 971
 - attr(*, "class")= chr "histogram"
972
> 
61157 ripley 973
> hist(sqrt(islands), breaks = 12, col = "lightblue", border = "pink")
56353 ripley 974
> ##-- For non-equidistant breaks, counts should NOT be graphed unscaled:
975
> r <- hist(sqrt(islands), breaks = c(4*0:5, 10*3:5, 70, 100, 140),
61169 ripley 976
+           col = "blue1")
977
> text(r$mids, r$density, r$counts, adj = c(.5, -.5), col = "blue3")
56353 ripley 978
> sapply(r[2:3], sum)
61587 ripley 979
   counts   density 
980
48.000000  0.215625 
56353 ripley 981
> sum(r$density * diff(r$breaks)) # == 1
982
[1] 1
983
> lines(r, lty = 3, border = "purple") # -> lines.histogram(*)
984
> par(op)
985
> 
986
> require(utils) # for str
61157 ripley 987
> str(hist(islands, breaks = 12, plot =  FALSE)) #-> 10 (~= 12) breaks
61587 ripley 988
List of 6
989
 $ breaks  : num [1:10] 0 2000 4000 6000 8000 10000 12000 14000 16000 18000
990
 $ counts  : int [1:9] 41 2 1 1 1 1 0 0 1
991
 $ density : num [1:9] 4.27e-04 2.08e-05 1.04e-05 1.04e-05 1.04e-05 ...
992
 $ mids    : num [1:9] 1000 3000 5000 7000 9000 11000 13000 15000 17000
993
 $ xname   : chr "islands"
994
 $ equidist: logi TRUE
56353 ripley 995
 - attr(*, "class")= chr "histogram"
61157 ripley 996
> str(hist(islands, breaks = c(12,20,36,80,200,1000,17000), plot = FALSE))
61587 ripley 997
List of 6
998
 $ breaks  : num [1:7] 12 20 36 80 200 1000 17000
999
 $ counts  : int [1:6] 12 11 8 6 4 7
1000
 $ density : num [1:6] 0.03125 0.014323 0.003788 0.001042 0.000104 ...
1001
 $ mids    : num [1:6] 16 28 58 140 600 9000
1002
 $ xname   : chr "islands"
1003
 $ equidist: logi FALSE
56353 ripley 1004
 - attr(*, "class")= chr "histogram"
1005
> 
61157 ripley 1006
> hist(islands, breaks = c(12,20,36,80,200,1000,17000), freq = TRUE,
56353 ripley 1007
+      main = "WRONG histogram") # and warning
1008
Warning in plot.histogram(r, freq = freq1, col = col, border = border, angle = angle,  :
60841 ripley 1009
  the AREAS in the plot are wrong -- rather use 'freq = FALSE'
56353 ripley 1010
> 
1011
> require(stats)
1012
> set.seed(14)
1013
> x <- rchisq(100, df = 4)
1014
> ## Don't show: 
1015
> op <- par(mfrow = 2:1, mgp = c(1.5, 0.6, 0), mar = .1 + c(3,3:1))
1016
> ## End Don't show
1017
> ## Comparing data with a model distribution should be done with qqplot()!
61157 ripley 1018
> qqplot(x, qchisq(ppoints(x), df = 4)); abline(0, 1, col = 2, lty = 2)
56353 ripley 1019
> 
1020
> ## if you really insist on using hist() ... :
1021
> hist(x, freq = FALSE, ylim = c(0, 0.2))
1022
> curve(dchisq(x, df = 4), col = 2, lty = 2, lwd = 2, add = TRUE)
1023
> ## Don't show: 
1024
> par(op)
1025
> ## End Don't show
1026
> 
1027
> 
1028
> 
1029
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1030
> cleanEx()
1031
> nameEx("identify")
1032
> ### * identify
1033
> 
1034
> flush(stderr()); flush(stdout())
1035
> 
1036
> ### Name: identify
1037
> ### Title: Identify Points in a Scatter Plot
1038
> ### Aliases: identify identify.default
1039
> ### Keywords: iplot
1040
> 
1041
> ### ** Examples
1042
> 
1043
> ## A function to use identify to select points, and overplot the
1044
> ## points with another symbol as they are selected
61157 ripley 1045
> identifyPch <- function(x, y = NULL, n = length(x), pch = 19, ...)
56353 ripley 1046
+ {
1047
+     xy <- xy.coords(x, y); x <- xy$x; y <- xy$y
1048
+     sel <- rep(FALSE, length(x)); res <- integer(0)
1049
+     while(sum(sel) < n) {
61157 ripley 1050
+         ans <- identify(x[!sel], y[!sel], n = 1, plot = FALSE, ...)
56353 ripley 1051
+         if(!length(ans)) break
1052
+         ans <- which(!sel)[ans]
1053
+         points(x[ans], y[ans], pch = pch)
1054
+         sel[ans] <- TRUE
1055
+         res <- c(res, ans)
1056
+     }
1057
+     res
1058
+ }
1059
> 
1060
> 
1061
> 
1062
> cleanEx()
1063
> nameEx("image")
1064
> ### * image
1065
> 
1066
> flush(stderr()); flush(stdout())
1067
> 
1068
> ### Name: image
1069
> ### Title: Display a Color Image
1070
> ### Aliases: image image.default
1071
> ### Keywords: hplot aplot
1072
> 
1073
> ### ** Examples
1074
> 
1075
> require(grDevices) # for colours
61157 ripley 1076
> x <- y <- seq(-4*pi, 4*pi, len = 27)
56353 ripley 1077
> r <- sqrt(outer(x^2, y^2, "+"))
61157 ripley 1078
> image(z = z <- cos(r^2)*exp(-r/6), col  = gray((0:32)/32))
56353 ripley 1079
> image(z, axes = FALSE, main = "Math can be beautiful ...",
1080
+       xlab = expression(cos(r^2) * e^{-r/6}))
1081
> contour(z, add = TRUE, drawlabels = FALSE)
1082
> 
1083
> # Volcano data visualized as matrix. Need to transpose and flip
1084
> # matrix horizontally.
1085
> image(t(volcano)[ncol(volcano):1,])
1086
> 
1087
> # A prettier display of the volcano
1088
> x <- 10*(1:nrow(volcano))
1089
> y <- 10*(1:ncol(volcano))
1090
> image(x, y, volcano, col = terrain.colors(100), axes = FALSE)
1091
> contour(x, y, volcano, levels = seq(90, 200, by = 5),
1092
+         add = TRUE, col = "peru")
1093
> axis(1, at = seq(100, 800, by = 100))
1094
> axis(2, at = seq(100, 600, by = 100))
1095
> box()
1096
> title(main = "Maunga Whau Volcano", font.main = 4)
1097
> 
1098
> 
1099
> 
1100
> cleanEx()
1101
> nameEx("layout")
1102
> ### * layout
1103
> 
1104
> flush(stderr()); flush(stdout())
1105
> 
1106
> ### Name: layout
1107
> ### Title: Specifying Complex Plot Arrangements
1108
> ### Aliases: layout layout.show lcm
1109
> ### Keywords: iplot dplot environment
1110
> 
1111
> ### ** Examples
1112
> 
1113
> def.par <- par(no.readonly = TRUE) # save default, for resetting...
1114
> 
1115
> ## divide the device into two rows and two columns
1116
> ## allocate figure 1 all of row 1
1117
> ## allocate figure 2 the intersection of column 2 and row 2
1118
> layout(matrix(c(1,1,0,2), 2, 2, byrow = TRUE))
1119
> ## show the regions that have been allocated to each plot
1120
> layout.show(2)
1121
> 
1122
> ## divide device into two rows and two columns
1123
> ## allocate figure 1 and figure 2 as above
1124
> ## respect relations between widths and heights
61157 ripley 1125
> nf <- layout(matrix(c(1,1,0,2), 2, 2, byrow = TRUE), respect = TRUE)
56353 ripley 1126
> layout.show(nf)
1127
> 
1128
> ## create single figure which is 5cm square
61157 ripley 1129
> nf <- layout(matrix(1), widths = lcm(5), heights = lcm(5))
56353 ripley 1130
> layout.show(nf)
1131
> 
1132
> 
1133
> ##-- Create a scatterplot with marginal histograms -----
1134
> 
1135
> x <- pmin(3, pmax(-3, stats::rnorm(50)))
1136
> y <- pmin(3, pmax(-3, stats::rnorm(50)))
61157 ripley 1137
> xhist <- hist(x, breaks = seq(-3,3,0.5), plot = FALSE)
1138
> yhist <- hist(y, breaks = seq(-3,3,0.5), plot = FALSE)
56353 ripley 1139
> top <- max(c(xhist$counts, yhist$counts))
61169 ripley 1140
> xrange <- c(-3, 3)
1141
> yrange <- c(-3, 3)
61157 ripley 1142
> nf <- layout(matrix(c(2,0,1,3),2,2,byrow = TRUE), c(3,1), c(1,3), TRUE)
56353 ripley 1143
> layout.show(nf)
1144
> 
61157 ripley 1145
> par(mar = c(3,3,1,1))
1146
> plot(x, y, xlim = xrange, ylim = yrange, xlab = "", ylab = "")
1147
> par(mar = c(0,3,1,1))
1148
> barplot(xhist$counts, axes = FALSE, ylim = c(0, top), space = 0)
1149
> par(mar = c(3,0,1,1))
1150
> barplot(yhist$counts, axes = FALSE, xlim = c(0, top), space = 0, horiz = TRUE)
56353 ripley 1151
> 
61169 ripley 1152
> par(def.par)  #- reset to default
56353 ripley 1153
> 
1154
> 
1155
> 
1156
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1157
> cleanEx()
1158
> nameEx("legend")
1159
> ### * legend
1160
> 
1161
> flush(stderr()); flush(stdout())
1162
> 
1163
> ### Name: legend
1164
> ### Title: Add Legends to Plots
1165
> ### Aliases: legend
1166
> ### Keywords: aplot
1167
> 
1168
> ### ** Examples
1169
> 
1170
> ## Run the example in '?matplot' or the following:
1171
> leg.txt <- c("Setosa     Petals", "Setosa     Sepals",
1172
+              "Versicolor Petals", "Versicolor Sepals")
1173
> y.leg <- c(4.5, 3, 2.1, 1.4, .7)
1174
> cexv  <- c(1.2, 1, 4/5, 2/3, 1/2)
61255 ripley 1175
> matplot(c(1, 8), c(0, 4.5), type = "n", xlab = "Length", ylab = "Width",
56353 ripley 1176
+         main = "Petal and Sepal Dimensions in Iris Blossoms")
1177
> for (i in seq(cexv)) {
61255 ripley 1178
+   text  (1, y.leg[i] - 0.1, paste("cex=", formatC(cexv[i])), cex = 0.8, adj = 0)
56353 ripley 1179
+   legend(3, y.leg[i], leg.txt, pch = "sSvV", col = c(1, 3), cex = cexv[i])
1180
+ }
1181
> 
1182
> ## 'merge = TRUE' for merging lines & points:
1183
> x <- seq(-pi, pi, len = 65)
1184
> plot(x, sin(x), type = "l", ylim = c(-1.2, 1.8), col = 3, lty = 2)
1185
> points(x, cos(x), pch = 3, col = 4)
1186
> lines(x, tan(x), type = "b", lty = 1, pch = 4, col = 6)
61258 ripley 1187
> title("legend(..., lty = c(2, -1, 1), pch = c(NA, 3, 4), merge = TRUE)",
56353 ripley 1188
+       cex.main = 1.1)
61255 ripley 1189
> legend(-1, 1.9, c("sin", "cos", "tan"), col = c(3, 4, 6),
61258 ripley 1190
+        text.col = "green4", lty = c(2, -1, 1), pch = c(NA, 3, 4),
61169 ripley 1191
+        merge = TRUE, bg = "gray90")
56353 ripley 1192
> 
1193
> ## right-justifying a set of labels: thanks to Uwe Ligges
1194
> x <- 1:5; y1 <- 1/x; y2 <- 2/x
61157 ripley 1195
> plot(rep(x, 2), c(y1, y2), type = "n", xlab = "x", ylab = "y")
1196
> lines(x, y1); lines(x, y2, lty = 2)
56353 ripley 1197
> temp <- legend("topright", legend = c(" ", " "),
1198
+                text.width = strwidth("1,000,000"),
1199
+                lty = 1:2, xjust = 1, yjust = 1,
1200
+                title = "Line Types")
1201
> text(temp$rect$left + temp$rect$w, temp$text$y,
61157 ripley 1202
+      c("1,000", "1,000,000"), pos = 2)
56353 ripley 1203
> 
1204
> 
1205
> ##--- log scaled Examples ------------------------------
1206
> leg.txt <- c("a one", "a two")
1207
> 
61255 ripley 1208
> par(mfrow = c(2, 2))
56353 ripley 1209
> for(ll in c("","x","y","xy")) {
61157 ripley 1210
+   plot(2:10, log = ll, main = paste0("log = '", ll, "'"))
1211
+   abline(1, 1)
61255 ripley 1212
+   lines(2:3, 3:4, col = 2)
1213
+   points(2, 2, col = 3)
61157 ripley 1214
+   rect(2, 3, 3, 2, col = 4)
1215
+   text(c(3,3), 2:3, c("rect(2,3,3,2, col=4)",
61255 ripley 1216
+                       "text(c(3,3),2:3,\"c(rect(...)\")"), adj = c(0, 0.3))
61157 ripley 1217
+   legend(list(x = 2,y = 8), legend = leg.txt, col = 2:3, pch = 1:2,
61169 ripley 1218
+          lty = 1, merge = TRUE)   #, trace = TRUE)
56353 ripley 1219
+ }
61157 ripley 1220
> par(mfrow = c(1,1))
56353 ripley 1221
> 
1222
> ##-- Math expressions:  ------------------------------
1223
> x <- seq(-pi, pi, len = 65)
61157 ripley 1224
> plot(x, sin(x), type = "l", col = 2, xlab = expression(phi),
56353 ripley 1225
+      ylab = expression(f(phi)))
61157 ripley 1226
> abline(h = -1:1, v = pi/2*(-6:6), col = "gray90")
56353 ripley 1227
> lines(x, cos(x), col = 3, lty = 2)
61169 ripley 1228
> ex.cs1 <- expression(plain(sin) * phi,  paste("cos", phi))  # 2 ways
61157 ripley 1229
> utils::str(legend(-3, .9, ex.cs1, lty = 1:2, plot = FALSE,
61255 ripley 1230
+            adj = c(0, 0.6)))  # adj y !
56353 ripley 1231
List of 2
1232
 $ rect:List of 4
1233
  ..$ w   : num 1.2
1234
  ..$ h   : num 0.251
1235
  ..$ left: num -3
1236
  ..$ top : num 0.9
1237
 $ text:List of 2
1238
  ..$ x: num [1:2] -2.29 -2.29
1239
  ..$ y: num [1:2] 0.816 0.733
61255 ripley 1240
> legend(-3, 0.9, ex.cs1, lty = 1:2, col = 2:3,  adj = c(0, 0.6))
56353 ripley 1241
> 
1242
> require(stats)
1243
> x <- rexp(100, rate = .5)
1244
> hist(x, main = "Mean and Median of a Skewed Distribution")
61157 ripley 1245
> abline(v = mean(x),   col = 2, lty = 2, lwd = 2)
1246
> abline(v = median(x), col = 3, lty = 3, lwd = 2)
1247
> ex12 <- expression(bar(x) == sum(over(x[i], n), i == 1, n),
1248
+                    hat(x) == median(x[i], i == 1, n))
61255 ripley 1249
> utils::str(legend(4.1, 30, ex12, col = 2:3, lty = 2:3, lwd = 2))
56353 ripley 1250
List of 2
1251
 $ rect:List of 4
1252
  ..$ w   : num 4.27
1253
  ..$ h   : num 6.78
1254
  ..$ left: num 4.1
1255
  ..$ top : num 30
1256
 $ text:List of 2
1257
  ..$ x: num [1:2] 5.22 5.22
1258
  ..$ y: num [1:2] 27.3 24.6
1259
> 
1260
> ## 'Filled' boxes -- for more, see example(plot.factor)
61157 ripley 1261
> op <- par(bg = "white") # to get an opaque box for the legend
56353 ripley 1262
> plot(cut(weight, 3) ~ group, data = PlantGrowth, col = NULL,
1263
+      density = 16*(1:3))
1264
> par(op)
1265
> 
1266
> ## Using 'ncol' :
1267
> x <- 0:64/64
1268
> matplot(x, outer(x, 1:7, function(x, k) sin(k * pi * x)),
1269
+         type = "o", col = 1:7, ylim = c(-1, 1.5), pch = "*")
61157 ripley 1270
> op <- par(bg = "antiquewhite1")
1271
> legend(0, 1.5, paste("sin(", 1:7, "pi * x)"), col = 1:7, lty = 1:7,
56353 ripley 1272
+        pch = "*", ncol = 4, cex = 0.8)
61157 ripley 1273
> legend(.8,1.2, paste("sin(", 1:7, "pi * x)"), col = 1:7, lty = 1:7,
56353 ripley 1274
+        pch = "*", cex = 0.8)
61157 ripley 1275
> legend(0, -.1, paste("sin(", 1:4, "pi * x)"), col = 1:4, lty = 1:4,
56353 ripley 1276
+        ncol = 2, cex = 0.8)
61157 ripley 1277
> legend(0, -.4, paste("sin(", 5:7, "pi * x)"), col = 4:6,  pch = 24,
56353 ripley 1278
+        ncol = 2, cex = 1.5, lwd = 2, pt.bg = "pink", pt.cex = 1:3)
1279
> par(op)
1280
> 
1281
> ## point covering line :
1282
> y <- sin(3*pi*x)
61157 ripley 1283
> plot(x, y, type = "l", col = "blue",
56353 ripley 1284
+     main = "points with bg & legend(*, pt.bg)")
61157 ripley 1285
> points(x, y, pch = 21, bg = "white")
1286
> legend(.4,1, "sin(c x)", pch = 21, pt.bg = "white", lty = 1, col = "blue")
56353 ripley 1287
> 
1288
> ## legends with titles at different locations
61169 ripley 1289
> plot(x, y, type = "n")
61157 ripley 1290
> legend("bottomright", "(x,y)", pch = 1, title = "bottomright")
1291
> legend("bottom", "(x,y)", pch = 1, title = "bottom")
1292
> legend("bottomleft", "(x,y)", pch = 1, title = "bottomleft")
1293
> legend("left", "(x,y)", pch = 1, title = "left")
1294
> legend("topleft", "(x,y)", pch = 1, title = "topleft, inset = .05",
56353 ripley 1295
+        inset = .05)
61157 ripley 1296
> legend("top", "(x,y)", pch = 1, title = "top")
1297
> legend("topright", "(x,y)", pch = 1, title = "topright, inset = .02",
56353 ripley 1298
+        inset = .02)
61157 ripley 1299
> legend("right", "(x,y)", pch = 1, title = "right")
1300
> legend("center", "(x,y)", pch = 1, title = "center")
56353 ripley 1301
> 
57622 maechler 1302
> # using text.font (and text.col):
61255 ripley 1303
> op <- par(mfrow = c(2, 2), mar = rep(2.1, 4))
57622 maechler 1304
> c6 <- terrain.colors(10)[1:6]
1305
> for(i in 1:4) {
61157 ripley 1306
+    plot(1, type = "n", axes = FALSE, ann = FALSE); title(paste("text.font =",i))
57622 maechler 1307
+    legend("top", legend = LETTERS[1:6], col = c6,
61157 ripley 1308
+           ncol = 2, cex = 2, lwd = 3, text.font = i, text.col = c6)
57622 maechler 1309
+ }
1310
> par(op)
56353 ripley 1311
> 
1312
> 
57622 maechler 1313
> 
56353 ripley 1314
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1315
> cleanEx()
1316
> nameEx("lines")
1317
> ### * lines
1318
> 
1319
> flush(stderr()); flush(stdout())
1320
> 
1321
> ### Name: lines
1322
> ### Title: Add Connected Line Segments to a Plot
1323
> ### Aliases: lines lines.default
1324
> ### Keywords: aplot
1325
> 
1326
> ### ** Examples
1327
> 
1328
> # draw a smooth line through a scatter plot
61157 ripley 1329
> plot(cars, main = "Stopping Distance versus Speed")
56353 ripley 1330
> lines(stats::lowess(cars))
1331
> 
1332
> 
1333
> 
1334
> cleanEx()
1335
> nameEx("matplot")
1336
> ### * matplot
1337
> 
1338
> flush(stderr()); flush(stdout())
1339
> 
1340
> ### Name: matplot
1341
> ### Title: Plot Columns of Matrices
1342
> ### Aliases: matplot matpoints matlines
1343
> ### Keywords: hplot aplot array
1344
> 
1345
> ### ** Examples
1346
> 
1347
> require(grDevices)
1348
> matplot((-4:5)^2, main = "Quadratic") # almost identical to plot(*)
1349
> sines <- outer(1:20, 1:4, function(x, y) sin(x / 20 * pi * y))
1350
> matplot(sines, pch = 1:4, type = "o", col = rainbow(ncol(sines)))
1351
> matplot(sines, type = "b", pch = 21:23, col = 2:5, bg = 2:5,
1352
+         main = "matplot(...., pch = 21:23, bg = 2:5)")
1353
> 
1354
> x <- 0:50/50
1355
> matplot(x, outer(x, 1:8, function(x, k) sin(k*pi * x)),
1356
+         ylim = c(-2,2), type = "plobcsSh",
1357
+         main= "matplot(,type = \"plobcsSh\" )")
1358
> ## pch & type =  vector of 1-chars :
1359
> matplot(x, outer(x, 1:4, function(x, k) sin(k*pi * x)),
1360
+         pch = letters[1:4], type = c("b","p","o"))
1361
> 
1362
> lends <- c("round","butt","square")
1363
> matplot(matrix(1:12, 4), type="c", lty=1, lwd=10, lend=lends)
1364
> text(cbind(2.5, 2*c(1,3,5)-.4), lends, col= 1:3, cex = 1.5)
1365
> 
1366
> table(iris$Species) # is data.frame with 'Species' factor
1367
 
1368
    setosa versicolor  virginica 
1369
        50         50         50 
1370
> iS <- iris$Species == "setosa"
1371
> iV <- iris$Species == "versicolor"
1372
> op <- par(bg = "bisque")
61157 ripley 1373
> matplot(c(1, 8), c(0, 4.5), type =  "n", xlab = "Length", ylab = "Width",
56353 ripley 1374
+         main = "Petal and Sepal Dimensions in Iris Blossoms")
1375
> matpoints(iris[iS,c(1,3)], iris[iS,c(2,4)], pch = "sS", col = c(2,4))
1376
> matpoints(iris[iV,c(1,3)], iris[iV,c(2,4)], pch = "vV", col = c(2,4))
1377
> legend(1, 4, c("    Setosa Petals", "    Setosa Sepals",
1378
+                "Versicolor Petals", "Versicolor Sepals"),
1379
+        pch = "sSvV", col = rep(c(2,4), 2))
1380
> 
1381
> nam.var <- colnames(iris)[-5]
1382
> nam.spec <- as.character(iris[1+50*0:2, "Species"])
1383
> iris.S <- array(NA, dim = c(50,4,3),
1384
+                 dimnames = list(NULL, nam.var, nam.spec))
1385
> for(i in 1:3) iris.S[,,i] <- data.matrix(iris[1:50+50*(i-1), -5])
1386
> 
61169 ripley 1387
> matplot(iris.S[, "Petal.Length",], iris.S[, "Petal.Width",], pch = "SCV",
61157 ripley 1388
+         col = rainbow(3, start = 0.8, end = 0.1),
56353 ripley 1389
+         sub = paste(c("S", "C", "V"), dimnames(iris.S)[[3]],
1390
+                     sep = "=", collapse= ",  "),
1391
+         main = "Fisher's Iris Data")
1392
> par(op)
1393
> 
1394
> 
1395
> 
1396
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1397
> cleanEx()
1398
> nameEx("mosaicplot")
1399
> ### * mosaicplot
1400
> 
1401
> flush(stderr()); flush(stdout())
1402
> 
1403
> ### Name: mosaicplot
1404
> ### Title: Mosaic Plots
1405
> ### Aliases: mosaicplot mosaicplot.default mosaicplot.formula
1406
> ### Keywords: hplot
1407
> 
1408
> ### ** Examples
1409
> 
1410
> require(stats)
1411
> mosaicplot(Titanic, main = "Survival on the Titanic", color = TRUE)
1412
> ## Formula interface for tabulated data:
1413
> mosaicplot(~ Sex + Age + Survived, data = Titanic, color = TRUE)
1414
> 
1415
> mosaicplot(HairEyeColor, shade = TRUE)
1416
> ## Independence model of hair and eye color and sex.  Indicates that
61435 ripley 1417
> ## there are more blue eyed blonde females than expected in the case
56353 ripley 1418
> ## of independence and too few brown eyed blonde females.
1419
> ## The corresponding model is:
1420
> fm <- loglin(HairEyeColor, list(1, 2, 3))
1421
2 iterations: deviation 5.684342e-14 
1422
> pchisq(fm$pearson, fm$df, lower.tail = FALSE)
1423
[1] 5.320872e-23
1424
> 
1425
> mosaicplot(HairEyeColor, shade = TRUE, margin = list(1:2, 3))
1426
> ## Model of joint independence of sex from hair and eye color.  Males
1427
> ## are underrepresented among people with brown hair and eyes, and are
1428
> ## overrepresented among people with brown hair and blue eyes.
1429
> ## The corresponding model is:
1430
> fm <- loglin(HairEyeColor, list(1:2, 3))
1431
2 iterations: deviation 5.684342e-14 
1432
> pchisq(fm$pearson, fm$df, lower.tail = FALSE)
1433
[1] 0.1891745
1434
> 
1435
> ## Formula interface for raw data: visualize cross-tabulation of numbers
1436
> ## of gears and carburettors in Motor Trend car data.
1437
> mosaicplot(~ gear + carb, data = mtcars, color = TRUE, las = 1)
1438
> # color recycling
1439
> mosaicplot(~ gear + carb, data = mtcars, color = 2:3, las = 1)
1440
> 
1441
> 
1442
> 
1443
> cleanEx()
1444
> nameEx("mtext")
1445
> ### * mtext
1446
> 
1447
> flush(stderr()); flush(stdout())
1448
> 
1449
> ### Name: mtext
1450
> ### Title: Write Text into the Margins of a Plot
1451
> ### Aliases: mtext
1452
> ### Keywords: aplot
1453
> 
1454
> ### ** Examples
1455
> 
61157 ripley 1456
> plot(1:10, (-4:5)^2, main = "Parabola Points", xlab = "xlab")
56353 ripley 1457
> mtext("10 of them")
1458
> for(s in 1:4)
61169 ripley 1459
+     mtext(paste("mtext(..., line= -1, {side, col, font} = ", s,
56353 ripley 1460
+           ", cex = ", (1+s)/2, ")"), line = -1,
61157 ripley 1461
+           side = s, col = s, font = s, cex = (1+s)/2)
56353 ripley 1462
> mtext("mtext(..., line= -2)", line = -2)
61157 ripley 1463
> mtext("mtext(..., line= -2, adj = 0)", line = -2, adj = 0)
56353 ripley 1464
> ##--- log axis :
61169 ripley 1465
> plot(1:10, exp(1:10), log = "y", main = "log =\"y\"", xlab = "xlab")
61157 ripley 1466
> for(s in 1:4) mtext(paste("mtext(...,side=", s ,")"), side = s)
56353 ripley 1467
> 
1468
> 
1469
> 
1470
> cleanEx()
1471
> nameEx("pairs")
1472
> ### * pairs
1473
> 
1474
> flush(stderr()); flush(stdout())
1475
> 
1476
> ### Name: pairs
1477
> ### Title: Scatterplot Matrices
1478
> ### Aliases: pairs pairs.default pairs.formula
1479
> ### Keywords: hplot
1480
> 
1481
> ### ** Examples
1482
> 
1483
> pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species",
1484
+       pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)])
1485
> 
1486
> ## formula method
1487
> pairs(~ Fertility + Education + Catholic, data = swiss,
1488
+       subset = Education < 20, main = "Swiss data, Education < 20")
1489
> 
1490
> pairs(USJudgeRatings)
61011 maechler 1491
> ## show only lower triangle (and suppress labeling for whatever reason):
61157 ripley 1492
> pairs(USJudgeRatings, text.panel = NULL, upper.panel = NULL)
56353 ripley 1493
> 
1494
> ## put histograms on the diagonal
1495
> panel.hist <- function(x, ...)
1496
+ {
1497
+     usr <- par("usr"); on.exit(par(usr))
1498
+     par(usr = c(usr[1:2], 0, 1.5) )
1499
+     h <- hist(x, plot = FALSE)
1500
+     breaks <- h$breaks; nB <- length(breaks)
1501
+     y <- h$counts; y <- y/max(y)
61157 ripley 1502
+     rect(breaks[-nB], 0, breaks[-1], y, col = "cyan", ...)
56353 ripley 1503
+ }
61157 ripley 1504
> pairs(USJudgeRatings[1:5], panel = panel.smooth,
1505
+       cex = 1.5, pch = 24, bg = "light blue",
1506
+       diag.panel = panel.hist, cex.labels = 2, font.labels = 2)
56353 ripley 1507
> 
1508
> ## put (absolute) correlations on the upper panels,
1509
> ## with size proportional to the correlations.
61157 ripley 1510
> panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
56353 ripley 1511
+ {
1512
+     usr <- par("usr"); on.exit(par(usr))
1513
+     par(usr = c(0, 1, 0, 1))
1514
+     r <- abs(cor(x, y))
61157 ripley 1515
+     txt <- format(c(r, 0.123456789), digits = digits)[1]
1516
+     txt <- paste0(prefix, txt)
56353 ripley 1517
+     if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
1518
+     text(0.5, 0.5, txt, cex = cex.cor * r)
1519
+ }
61157 ripley 1520
> pairs(USJudgeRatings, lower.panel = panel.smooth, upper.panel = panel.cor)
56353 ripley 1521
> 
59643 ripley 1522
> pairs(iris[-5], log = "xy") # plot all variables on log scale
62705 maechler 1523
> pairs(iris, log = 1:4, # log the first four
1524
+       main = "Lengths and Widths in [log]", line.main=1.5, oma=c(2,2,3,2))
56353 ripley 1525
> 
1526
> 
59643 ripley 1527
> 
56353 ripley 1528
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1529
> cleanEx()
1530
> nameEx("panel.smooth")
1531
> ### * panel.smooth
1532
> 
1533
> flush(stderr()); flush(stdout())
1534
> 
1535
> ### Name: panel.smooth
1536
> ### Title: Simple Panel Plot
1537
> ### Aliases: panel.smooth
1538
> ### Keywords: hplot dplot
1539
> 
1540
> ### ** Examples
1541
> 
61169 ripley 1542
> pairs(swiss, panel = panel.smooth, pch = ".")  # emphasize the smooths
1543
> pairs(swiss, panel = panel.smooth, lwd = 2, cex = 1.5, col = "blue")  # hmm...
56353 ripley 1544
> 
1545
> 
1546
> 
1547
> cleanEx()
1548
> nameEx("par")
1549
> ### * par
1550
> 
1551
> flush(stderr()); flush(stdout())
1552
> 
1553
> ### Name: par
1554
> ### Title: Set or Query Graphical Parameters
1555
> ### Aliases: par .Pars 'graphical parameter' 'graphical parameters'
1556
> ### Keywords: iplot dplot environment
1557
> 
1558
> ### ** Examples
1559
> 
1560
> op <- par(mfrow = c(2, 2), # 2 x 2 pictures on one plot
1561
+           pty = "s")       # square plotting region,
1562
>                            # independent of device size
1563
> 
1564
> ## At end of plotting, reset to previous settings:
1565
> par(op)
1566
> 
1567
> ## Alternatively,
1568
> op <- par(no.readonly = TRUE) # the whole list of settable par's.
1569
> ## do lots of plotting and par(.) calls, then reset:
1570
> par(op)
1571
> ## Note this is not in general good practice
1572
> 
1573
> par("ylog") # FALSE
1574
[1] FALSE
1575
> plot(1 : 12, log = "y")
1576
> par("ylog") # TRUE
1577
[1] TRUE
1578
> 
1579
> plot(1:2, xaxs = "i") # 'inner axis' w/o extra space
1580
> par(c("usr", "xaxp"))
1581
$usr
1582
[1] 1.00 2.00 0.96 2.04
1583
 
1584
$xaxp
1585
[1] 1 2 5
1586
 
1587
> 
1588
> ( nr.prof <-
61169 ripley 1589
+ c(prof.pilots = 16, lawyers = 11, farmers = 10, salesmen = 9, physicians = 9,
1590
+   mechanics = 6, policemen = 6, managers = 6, engineers = 5, teachers = 4,
1591
+   housewives = 3, students = 3, armed.forces = 1))
56353 ripley 1592
 prof.pilots      lawyers      farmers     salesmen   physicians    mechanics 
1593
          16           11           10            9            9            6 
1594
   policemen     managers    engineers     teachers   housewives     students 
1595
           6            6            5            4            3            3 
1596
armed.forces 
1597
           1 
1598
> par(las = 3)
1599
> barplot(rbind(nr.prof)) # R 0.63.2: shows alignment problem
61169 ripley 1600
> par(las = 0)  # reset to default
56353 ripley 1601
> 
1602
> require(grDevices) # for gray
1603
> ## 'fg' use:
61157 ripley 1604
> plot(1:12, type = "b", main = "'fg' : axes, ticks and box in gray",
1605
+      fg = gray(0.7), bty = "7" , sub = R.version.string)
56353 ripley 1606
> 
1607
> ex <- function() {
1608
+    old.par <- par(no.readonly = TRUE) # all par settings which
1609
+                                       # could be changed.
1610
+    on.exit(par(old.par))
1611
+    ## ...
1612
+    ## ... do lots of par() settings and plots
1613
+    ## ...
1614
+    invisible() #-- now,  par(old.par)  will be executed
1615
+ }
1616
> ex()
1617
> 
59180 maechler 1618
> ## Line types
1619
> showLty <- function(ltys, xoff = 0, ...) {
1620
+    stopifnot((n <- length(ltys)) >= 1)
1621
+    op <- par(mar = rep(.5,4)); on.exit(par(op))
61169 ripley 1622
+    plot(0:1, 0:1, type = "n", axes = FALSE, ann = FALSE)
59180 maechler 1623
+    y <- (n:1)/(n+1)
1624
+    clty <- as.character(ltys)
62642 hornik 1625
+    mytext <- function(x, y, txt)
1626
+       text(x, y, txt, adj = c(0, -.3), cex = 0.8, ...)
59180 maechler 1627
+    abline(h = y, lty = ltys, ...); mytext(xoff, y, clty)
1628
+    y <- y - 1/(3*(n+1))
62642 hornik 1629
+    abline(h = y, lty = ltys, lwd = 2, ...)
1630
+    mytext(1/8+xoff, y, paste(clty," lwd = 2"))
59180 maechler 1631
+ }
1632
> showLty(c("solid", "dashed", "dotted", "dotdash", "longdash", "twodash"))
61169 ripley 1633
> par(new = TRUE)  # the same:
61157 ripley 1634
> showLty(c("solid", "44", "13", "1343", "73", "2262"), xoff = .2, col = 2)
59180 maechler 1635
> showLty(c("11", "22", "33", "44",   "12", "13", "14",   "21", "31"))
56353 ripley 1636
> 
1637
> 
59180 maechler 1638
> 
56353 ripley 1639
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1640
> cleanEx()
1641
> nameEx("persp")
1642
> ### * persp
1643
> 
1644
> flush(stderr()); flush(stdout())
1645
> 
1646
> ### Name: persp
1647
> ### Title: Perspective Plots
1648
> ### Aliases: persp persp.default
1649
> ### Keywords: hplot aplot
1650
> 
1651
> ### ** Examples
1652
> 
1653
> require(grDevices) # for trans3d
1654
> ## More examples in  demo(persp) !!
1655
> ##                   -----------
1656
> 
1657
> # (1) The Obligatory Mathematical surface.
1658
> #     Rotated sinc function.
1659
> 
1660
> x <- seq(-10, 10, length= 30)
1661
> y <- x
61169 ripley 1662
> f <- function(x, y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
56353 ripley 1663
> z <- outer(x, y, f)
1664
> z[is.na(z)] <- 1
1665
> op <- par(bg = "white")
1666
> persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")
1667
> persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
1668
+       ltheta = 120, shade = 0.75, ticktype = "detailed",
1669
+       xlab = "X", ylab = "Y", zlab = "Sinc( r )"
1670
+ ) -> res
1671
> round(res, 3)
1672
      [,1]   [,2]   [,3]   [,4]
1673
[1,] 0.087 -0.025  0.043 -0.043
1674
[2,] 0.050  0.043 -0.075  0.075
1675
[3,] 0.000  0.074  0.042 -0.042
1676
[4,] 0.000 -0.273 -2.890  3.890
1677
> 
1678
> # (2) Add to existing persp plot - using trans3d() :
1679
> 
1680
> xE <- c(-10,10); xy <- expand.grid(xE, xE)
61157 ripley 1681
> points(trans3d(xy[,1], xy[,2], 6, pmat = res), col = 2, pch = 16)
1682
> lines (trans3d(x, y = 10, z = 6 + sin(x), pmat = res), col = 3)
56353 ripley 1683
> 
1684
> phi <- seq(0, 2*pi, len = 201)
1685
> r1 <- 7.725 # radius of 2nd maximum
1686
> xr <- r1 * cos(phi)
1687
> yr <- r1 * sin(phi)
1688
> lines(trans3d(xr,yr, f(xr,yr), res), col = "pink", lwd = 2)
1689
> ## (no hidden lines)
1690
> 
1691
> # (3) Visualizing a simple DEM model
1692
> 
1693
> z <- 2 * volcano        # Exaggerate the relief
1694
> x <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)
1695
> y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)
1696
> ## Don't draw the grid lines :  border = NA
1697
> par(bg = "slategray")
1698
> persp(x, y, z, theta = 135, phi = 30, col = "green3", scale = FALSE,
1699
+       ltheta = -120, shade = 0.75, border = NA, box = FALSE)
1700
> 
1701
> # (4) Surface colours corresponding to z-values
1702
> 
1703
> par(bg = "white")
1704
> x <- seq(-1.95, 1.95, length = 30)
1705
> y <- seq(-1.95, 1.95, length = 35)
61169 ripley 1706
> z <- outer(x, y, function(a, b) a*b^2)
56353 ripley 1707
> nrz <- nrow(z)
1708
> ncz <- ncol(z)
1709
> # Create a function interpolating colors in the range of specified colors
61435 ripley 1710
> jet.colors <- colorRampPalette( c("blue", "green") )
56353 ripley 1711
> # Generate the desired number of colors from this palette
1712
> nbcol <- 100
1713
> color <- jet.colors(nbcol)
1714
> # Compute the z-value at the facet centres
1715
> zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]
1716
> # Recode facet z-values into color indices
1717
> facetcol <- cut(zfacet, nbcol)
61157 ripley 1718
> persp(x, y, z, col = color[facetcol], phi = 30, theta = -30)
56353 ripley 1719
> 
1720
> par(op)
1721
> 
1722
> 
1723
> 
1724
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1725
> cleanEx()
1726
> nameEx("pie")
1727
> ### * pie
1728
> 
1729
> flush(stderr()); flush(stdout())
1730
> 
1731
> ### Name: pie
1732
> ### Title: Pie Charts
1733
> ### Aliases: pie
1734
> ### Keywords: hplot
1735
> 
1736
> ### ** Examples
1737
> 
1738
> require(grDevices)
1739
> pie(rep(1, 24), col = rainbow(24), radius = 0.9)
1740
> 
1741
> pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
1742
> names(pie.sales) <- c("Blueberry", "Cherry",
1743
+     "Apple", "Boston Cream", "Other", "Vanilla Cream")
1744
> pie(pie.sales) # default colours
1745
> pie(pie.sales, col = c("purple", "violetred1", "green3",
1746
+                        "cornsilk", "cyan", "white"))
61157 ripley 1747
> pie(pie.sales, col = gray(seq(0.4, 1.0, length = 6)))
56353 ripley 1748
> pie(pie.sales, density = 10, angle = 15 + 10 * 1:6)
61157 ripley 1749
> pie(pie.sales, clockwise = TRUE, main = "pie(*, clockwise = TRUE)")
61169 ripley 1750
> segments(0, 0, 0, 1, col = "red", lwd = 2)
1751
> text(0, 1, "init.angle = 90", col = "red")
56353 ripley 1752
> 
1753
> n <- 200
61169 ripley 1754
> pie(rep(1, n), labels = "", col = rainbow(n), border = NA,
56353 ripley 1755
+     main = "pie(*, labels=\"\", col=rainbow(n), border=NA,..")
1756
> 
1757
> 
1758
> 
1759
> cleanEx()
1760
> nameEx("plot")
1761
> ### * plot
1762
> 
1763
> flush(stderr()); flush(stdout())
1764
> 
1765
> ### Name: plot
1766
> ### Title: Generic X-Y Plotting
1767
> ### Aliases: plot
1768
> ### Keywords: hplot
1769
> 
1770
> ### ** Examples
1771
> 
1772
> require(stats)
1773
> plot(cars)
1774
> lines(lowess(cars))
1775
> 
56579 ripley 1776
> plot(sin, -pi, 2*pi) # see ?plot.function
56353 ripley 1777
> 
1778
> ## Discrete Distribution Plot:
61169 ripley 1779
> plot(table(rpois(100, 5)), type = "h", col = "red", lwd = 10,
1780
+      main = "rpois(100, lambda = 5)")
56353 ripley 1781
> 
1782
> ## Simple quantiles/ECDF, see ecdf() {library(stats)} for a better one:
1783
> plot(x <- sort(rnorm(47)), type = "s", main = "plot(x, type = \"s\")")
1784
> points(x, cex = .5, col = "dark red")
1785
> 
1786
> 
1787
> 
1788
> cleanEx()
1789
> nameEx("plot.dataframe")
1790
> ### * plot.dataframe
1791
> 
1792
> flush(stderr()); flush(stdout())
1793
> 
1794
> ### Name: plot.data.frame
1795
> ### Title: Plot Method for Data Frames
1796
> ### Aliases: plot.data.frame
1797
> ### Keywords: hplot methods
1798
> 
1799
> ### ** Examples
1800
> 
61157 ripley 1801
> plot(OrchardSprays[1], method = "jitter")
56353 ripley 1802
> plot(OrchardSprays[c(4,1)])
1803
> plot(OrchardSprays)
1804
> 
1805
> plot(iris)
1806
> plot(iris[5:4])
1807
> plot(women)
1808
> 
1809
> 
1810
> 
1811
> cleanEx()
1812
> nameEx("plot.default")
1813
> ### * plot.default
1814
> 
1815
> flush(stderr()); flush(stdout())
1816
> 
1817
> ### Name: plot.default
1818
> ### Title: The Default Scatterplot Function
1819
> ### Aliases: plot.default
1820
> ### Keywords: hplot
1821
> 
1822
> ### ** Examples
1823
> 
1824
> Speed <- cars$speed
1825
> Distance <- cars$dist
61169 ripley 1826
> plot(Speed, Distance, panel.first = grid(8, 8),
56353 ripley 1827
+      pch = 0, cex = 1.2, col = "blue")
1828
> plot(Speed, Distance,
1829
+      panel.first = lines(stats::lowess(Speed, Distance), lty = "dashed"),
1830
+      pch = 0, cex = 1.2, col = "blue")
1831
> 
1832
> ## Show the different plot types
1833
> x <- 0:12
1834
> y <- sin(pi/5 * x)
1835
> op <- par(mfrow = c(3,3), mar = .1+ c(2,2,3,1))
1836
> for (tp in c("p","l","b",  "c","o","h",  "s","S","n")) {
61157 ripley 1837
+    plot(y ~ x, type = tp, main = paste0("plot(*, type = \"", tp, "\")"))
56353 ripley 1838
+    if(tp == "S") {
61169 ripley 1839
+       lines(x, y, type = "s", col = "red", lty = 2)
61157 ripley 1840
+       mtext("lines(*, type = \"s\", ...)", col = "red", cex = 0.8)
56353 ripley 1841
+    }
1842
+ }
1843
> par(op)
1844
> 
1845
> ##--- Log-Log Plot  with  custom axes
61169 ripley 1846
> lx <- seq(1, 5, length = 41)
56353 ripley 1847
> yl <- expression(e^{-frac(1,2) * {log[10](x)}^2})
1848
> y <- exp(-.5*lx^2)
61157 ripley 1849
> op <- par(mfrow = c(2,1), mar = par("mar")+c(0,1,0,0))
1850
> plot(10^lx, y, log = "xy", type = "l", col = "purple",
1851
+      main = "Log-Log plot", ylab = yl, xlab = "x")
61169 ripley 1852
> plot(10^lx, y, log = "xy", type = "o", pch = ".", col = "forestgreen",
61157 ripley 1853
+      main = "Log-Log plot with custom axes", ylab = yl, xlab = "x",
56353 ripley 1854
+      axes = FALSE, frame.plot = TRUE)
1855
> my.at <- 10^(1:5)
61157 ripley 1856
> axis(1, at = my.at, labels = formatC(my.at, format = "fg"))
56353 ripley 1857
> at.y <- 10^(-5:-1)
61157 ripley 1858
> axis(2, at = at.y, labels = formatC(at.y, format = "fg"), col.axis = "red")
56353 ripley 1859
> par(op)
1860
> 
1861
> 
1862
> 
1863
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1864
> cleanEx()
1865
> nameEx("plot.design")
1866
> ### * plot.design
1867
> 
1868
> flush(stderr()); flush(stdout())
1869
> 
1870
> ### Name: plot.design
1871
> ### Title: Plot Univariate Effects of a Design or Model
1872
> ### Aliases: plot.design
1873
> ### Keywords: hplot
1874
> 
1875
> ### ** Examples
1876
> 
1877
> require(stats)
61169 ripley 1878
> plot.design(warpbreaks)  # automatic for data frame with one numeric var.
56353 ripley 1879
> 
1880
> Form <- breaks ~ wool + tension
1881
> summary(fm1 <- aov(Form, data = warpbreaks))
57044 ripley 1882
            Df Sum Sq Mean Sq F value  Pr(>F)   
1883
wool         1    451   450.7   3.339 0.07361 . 
1884
tension      2   2034  1017.1   7.537 0.00138 **
1885
Residuals   50   6748   135.0                   
56353 ripley 1886
---
61435 ripley 1887
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
61169 ripley 1888
> plot.design(       Form, data = warpbreaks, col = 2)  # same as above
56353 ripley 1889
> 
1890
> ## More than one y :
1891
> utils::str(esoph)
1892
'data.frame':	88 obs. of  5 variables:
1893
 $ agegp    : Ord.factor w/ 6 levels "25-34"<"35-44"<..: 1 1 1 1 1 1 1 1 1 1 ...
1894
 $ alcgp    : Ord.factor w/ 4 levels "0-39g/day"<"40-79"<..: 1 1 1 1 2 2 2 2 3 3 ...
1895
 $ tobgp    : Ord.factor w/ 4 levels "0-9g/day"<"10-19"<..: 1 2 3 4 1 2 3 4 1 2 ...
1896
 $ ncases   : num  0 0 0 0 0 0 0 0 0 0 ...
1897
 $ ncontrols: num  40 10 6 5 27 7 4 7 2 1 ...
1898
> plot.design(esoph) ## two plots; if interactive you are "ask"ed
1899
> 
1900
> ## or rather, compare mean and median:
1901
> op <- par(mfcol = 1:2)
1902
> plot.design(ncases/ncontrols ~ ., data = esoph, ylim = c(0, 0.8))
1903
> plot.design(ncases/ncontrols ~ ., data = esoph, ylim = c(0, 0.8),
1904
+             fun = median)
1905
> par(op)
1906
> 
1907
> 
1908
> 
1909
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1910
> cleanEx()
1911
> nameEx("plot.factor")
1912
> ### * plot.factor
1913
> 
1914
> flush(stderr()); flush(stdout())
1915
> 
1916
> ### Name: plot.factor
1917
> ### Title: Plotting Factor Variables
1918
> ### Aliases: plot.factor
1919
> ### Keywords: hplot
1920
> 
1921
> ### ** Examples
1922
> 
1923
> require(grDevices)
61169 ripley 1924
> plot(weight ~ group, data = PlantGrowth)           # numeric vector ~ factor
1925
> plot(cut(weight, 2) ~ group, data = PlantGrowth)   # factor ~ factor
56353 ripley 1926
> ## passing "..." to spineplot() eventually:
1927
> plot(cut(weight, 3) ~ group, data = PlantGrowth,
1928
+      col = hcl(c(0, 120, 240), 50, 70))
1929
> 
61169 ripley 1930
> plot(PlantGrowth$group, axes = FALSE, main = "no axes")  # extremely silly
56353 ripley 1931
> 
1932
> 
1933
> 
1934
> cleanEx()
1935
> nameEx("plot.formula")
1936
> ### * plot.formula
1937
> 
1938
> flush(stderr()); flush(stdout())
1939
> 
1940
> ### Name: plot.formula
1941
> ### Title: Formula Notation for Scatterplots
1942
> ### Aliases: plot.formula lines.formula points.formula text.formula
1943
> ### Keywords: hplot aplot
1944
> 
1945
> ### ** Examples
1946
> 
1947
> op <- par(mfrow = c(2,1))
1948
> plot(Ozone ~ Wind, data = airquality, pch = as.character(Month))
1949
> plot(Ozone ~ Wind, data = airquality, pch = as.character(Month),
1950
+      subset = Month != 7)
1951
> par(op)
1952
> 
1953
> ## text.formula() can be very natural:
1954
> wb <- within(warpbreaks, {
1955
+     time <- seq_along(breaks); W.T <- wool:tension })
1956
> plot(breaks ~ time, data = wb, type = "b")
1957
> text(breaks ~ time, data = wb, label = W.T, col = 1+as.integer(wool))
1958
> 
1959
> 
1960
> 
1961
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
1962
> cleanEx()
1963
> nameEx("plot.table")
1964
> ### * plot.table
1965
> 
1966
> flush(stderr()); flush(stdout())
1967
> 
1968
> ### Name: plot.table
1969
> ### Title: Plot Methods for 'table' Objects
1970
> ### Aliases: plot.table lines.table points.table
1971
> ### Keywords: hplot category
1972
> 
1973
> ### ** Examples
1974
> 
1975
> ## 1-d tables
1976
> (Poiss.tab <- table(N = stats::rpois(200, lambda = 5)))
1977
N
1978
 1  2  3  4  5  6  7  8  9 10 11 
1979
 4 14 25 38 40 33 21 16  4  2  3 
1980
> plot(Poiss.tab, main = "plot(table(rpois(200, lambda = 5)))")
1981
> 
1982
> plot(table(state.division))
1983
> 
1984
> ## 4-D :
1985
> plot(Titanic, main ="plot(Titanic, main= *)")
1986
> 
1987
> 
1988
> 
1989
> 
1990
> cleanEx()
1991
> nameEx("plot.window")
1992
> ### * plot.window
1993
> 
1994
> flush(stderr()); flush(stdout())
1995
> 
1996
> ### Name: plot.window
1997
> ### Title: Set up World Coordinates for Graphics Window
1998
> ### Aliases: plot.window xlim ylim asp
1999
> ### Keywords: aplot
2000
> 
2001
> ### ** Examples
2002
> 
2003
> ##--- An example for the use of 'asp' :
2004
> require(stats)  # normally loaded
2005
> loc <- cmdscale(eurodist)
2006
> rx <- range(x <- loc[,1])
2007
> ry <- range(y <- -loc[,2])
61157 ripley 2008
> plot(x, y, type = "n", asp = 1, xlab = "", ylab = "")
56353 ripley 2009
> abline(h = pretty(rx, 10), v = pretty(ry, 10), col = "lightgray")
61157 ripley 2010
> text(x, y, labels(eurodist), cex = 0.8)
56353 ripley 2011
> 
2012
> 
2013
> 
2014
> cleanEx()
2015
> nameEx("plot.xy")
2016
> ### * plot.xy
2017
> 
2018
> flush(stderr()); flush(stdout())
2019
> 
2020
> ### Name: plot.xy
2021
> ### Title: Basic Internal Plot Function
2022
> ### Aliases: plot.xy
2023
> ### Keywords: aplot
2024
> 
2025
> ### ** Examples
2026
> 
2027
> points.default # to see how it calls "plot.xy(xy.coords(x, y), ...)"
2028
function (x, y = NULL, type = "p", ...) 
2029
plot.xy(xy.coords(x, y), type = type, ...)
63202 ripley 2030
<bytecode: 0x2332048>
56353 ripley 2031
<environment: namespace:graphics>
2032
> 
2033
> 
2034
> 
2035
> cleanEx()
2036
> nameEx("plothistogram")
2037
> ### * plothistogram
2038
> 
2039
> flush(stderr()); flush(stdout())
2040
> 
2041
> ### Name: plot.histogram
2042
> ### Title: Plot Histograms
2043
> ### Aliases: plot.histogram lines.histogram
2044
> ### Keywords: hplot iplot
2045
> 
2046
> ### ** Examples
2047
> 
2048
> (wwt <- hist(women$weight, nclass = 7, plot = FALSE))
2049
$breaks
2050
 [1] 115 120 125 130 135 140 145 150 155 160 165
2051
 
2052
$counts
2053
 [1] 3 1 2 2 1 1 2 1 1 1
2054
 
2055
$density
2056
 [1] 0.04000000 0.01333333 0.02666667 0.02666667 0.01333333 0.01333333
2057
 [7] 0.02666667 0.01333333 0.01333333 0.01333333
2058
 
2059
$mids
2060
 [1] 117.5 122.5 127.5 132.5 137.5 142.5 147.5 152.5 157.5 162.5
2061
 
2062
$xname
2063
[1] "women$weight"
2064
 
2065
$equidist
2066
[1] TRUE
2067
 
2068
attr(,"class")
2069
[1] "histogram"
2070
> plot(wwt, labels = TRUE) # default main & xlab using wwt$xname
2071
> plot(wwt, border = "dark blue", col = "light blue",
2072
+      main = "Histogram of 15 women's weights", xlab = "weight [pounds]")
2073
> 
2074
> ## Fake "lines" example, using non-default labels:
2075
> w2 <- wwt; w2$counts <- w2$counts - 1
2076
> lines(w2, col = "Midnight Blue", labels = ifelse(w2$counts, "> 1", "1"))
2077
> 
2078
> 
2079
> 
2080
> cleanEx()
2081
> nameEx("points")
2082
> ### * points
2083
> 
2084
> flush(stderr()); flush(stdout())
2085
> 
2086
> ### Name: points
2087
> ### Title: Add Points to a Plot
2088
> ### Aliases: points points.default pch
2089
> ### Keywords: aplot
2090
> 
2091
> ### ** Examples
2092
> 
2093
> require(stats) # for rnorm
61169 ripley 2094
> plot(-4:4, -4:4, type = "n")  # setting up coord. system
56353 ripley 2095
> points(rnorm(200), rnorm(200), col = "red")
2096
> points(rnorm(100)/2, rnorm(100)/2, col = "blue", cex = 1.5)
2097
> 
2098
> op <- par(bg = "light blue")
61169 ripley 2099
> x <- seq(0, 2*pi, len = 51)
56353 ripley 2100
> ## something "between type='b' and type='o'":
61157 ripley 2101
> plot(x, sin(x), type = "o", pch = 21, bg = par("bg"), col = "blue", cex = .6,
2102
+  main = 'plot(..., type="o", pch=21, bg=par("bg"))')
56353 ripley 2103
> par(op)
2104
> 
2105
> ## Not run: 
2106
> ##D ## The figure was produced by calls like
61157 ripley 2107
> ##D png("pch.png", height = 0.7, width = 7, res = 100, units = "in")
56353 ripley 2108
> ##D par(mar = rep(0,4))
61157 ripley 2109
> ##D plot(c(-1, 26), 0:1, type = "n", axes = FALSE)
56353 ripley 2110
> ##D text(0:25, 0.6, 0:25, cex = 0.5)
2111
> ##D points(0:25, rep(0.3, 26), pch = 0:25, bg = "grey")
2112
> ## End(Not run)
2113
> 
2114
> ##-------- Showing all the extra & some char graphics symbols ---------
2115
> pchShow <-
2116
+   function(extras = c("*",".", "o","O","0","+","-","|","%","#"),
2117
+            cex = 3, ## good for both .Device=="postscript" and "x11"
2118
+            col = "red3", bg = "gold", coltext = "brown", cextext = 1.2,
2119
+            main = paste("plot symbols :  points (...  pch = *, cex =",
2120
+                         cex,")"))
2121
+   {
2122
+     nex <- length(extras)
2123
+     np  <- 26 + nex
2124
+     ipch <- 0:(np-1)
2125
+     k <- floor(sqrt(np))
2126
+     dd <- c(-1,1)/2
2127
+     rx <- dd + range(ix <- ipch %/% k)
2128
+     ry <- dd + range(iy <- 3 + (k-1)- ipch %% k)
2129
+     pch <- as.list(ipch) # list with integers & strings
2130
+     if(nex > 0) pch[26+ 1:nex] <- as.list(extras)
61157 ripley 2131
+     plot(rx, ry, type = "n", axes  =  FALSE, xlab = "", ylab = "", main = main)
56353 ripley 2132
+     abline(v = ix, h = iy, col = "lightgray", lty = "dotted")
2133
+     for(i in 1:np) {
2134
+       pc <- pch[[i]]
2135
+       ## 'col' symbols with a 'bg'-colored interior (where available) :
2136
+       points(ix[i], iy[i], pch = pc, col = col, bg = bg, cex = cex)
2137
+       if(cextext > 0)
2138
+           text(ix[i] - 0.3, iy[i], pc, col = coltext, cex = cextext)
2139
+     }
2140
+   }
2141
> 
2142
> pchShow()
2143
> pchShow(c("o","O","0"), cex = 2.5)
2144
> pchShow(NULL, cex = 4, cextext = 0, main = NULL)
2145
> 
2146
> 
2147
> 
2148
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2149
> cleanEx()
2150
> nameEx("polygon")
2151
> ### * polygon
2152
> 
2153
> flush(stderr()); flush(stdout())
2154
> 
2155
> ### Name: polygon
2156
> ### Title: Polygon Drawing
2157
> ### Aliases: polygon
2158
> ### Keywords: aplot
2159
> 
2160
> ### ** Examples
2161
> 
61169 ripley 2162
> x <- c(1:9, 8:1)
2163
> y <- c(1, 2*(5:3), 2, -1, 17, 9, 8, 2:9)
2164
> op <- par(mfcol = c(3, 1))
2165
> for(xpd in c(FALSE, TRUE, NA)) {
56353 ripley 2166
+   plot(1:10, main = paste("xpd =", xpd))
61157 ripley 2167
+   box("figure", col = "pink", lwd = 3)
61169 ripley 2168
+   polygon(x, y, xpd = xpd, col = "orange", lty = 2, lwd = 2, border = "red")
56353 ripley 2169
+ }
2170
> par(op)
2171
> 
2172
> n <- 100
2173
> xx <- c(0:n, n:0)
61169 ripley 2174
> yy <- c(c(0, cumsum(stats::rnorm(n))), rev(c(0, cumsum(stats::rnorm(n)))))
61157 ripley 2175
> plot   (xx, yy, type = "n", xlab = "Time", ylab = "Distance")
2176
> polygon(xx, yy, col = "gray", border = "red")
56353 ripley 2177
> title("Distance Between Brownian Motions")
2178
> 
2179
> # Multiple polygons from NA values
2180
> # and recycling of col, border, and lty
61169 ripley 2181
> op <- par(mfrow = c(2, 1))
2182
> plot(c(1, 9), 1:2, type = "n")
56353 ripley 2183
> polygon(1:9, c(2,1,2,1,1,2,1,2,1),
61157 ripley 2184
+         col = c("red", "blue"),
2185
+         border = c("green", "yellow"),
2186
+         lwd = 3, lty = c("dashed", "solid"))
61169 ripley 2187
> plot(c(1, 9), 1:2, type = "n")
56353 ripley 2188
> polygon(1:9, c(2,1,2,1,NA,2,1,2,1),
61157 ripley 2189
+         col = c("red", "blue"),
2190
+         border = c("green", "yellow"),
2191
+         lwd = 3, lty = c("dashed", "solid"))
56353 ripley 2192
> par(op)
2193
> 
2194
> # Line-shaded polygons
61169 ripley 2195
> plot(c(1, 9), 1:2, type = "n")
56353 ripley 2196
> polygon(1:9, c(2,1,2,1,NA,2,1,2,1),
61157 ripley 2197
+         density = c(10, 20), angle = c(-45, 45))
56353 ripley 2198
> 
2199
> 
2200
> 
2201
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2202
> cleanEx()
2203
> nameEx("polypath")
2204
> ### * polypath
2205
> 
2206
> flush(stderr()); flush(stdout())
2207
> 
2208
> ### Name: polypath
2209
> ### Title: Path Drawing
2210
> ### Aliases: polypath
2211
> ### Keywords: aplot
2212
> 
2213
> ### ** Examples
2214
> 
2215
> plotPath <- function(x, y, col = "grey", rule = "winding") {
2216
+     plot.new()
2217
+     plot.window(range(x, na.rm = TRUE), range(y, na.rm = TRUE))
2218
+     polypath(x, y, col = col, rule = rule)
2219
+     if (!is.na(col))
2220
+         mtext(paste("Rule:", rule), side = 1, line = 0)
2221
+ }
2222
> 
2223
> plotRules <- function(x, y, title) {
2224
+     plotPath(x, y)
2225
+     plotPath(x, y, rule = "evenodd")
2226
+     mtext(title, side = 3, line = 0)
2227
+     plotPath(x, y, col = NA)
2228
+ }
2229
> 
2230
> op <- par(mfrow = c(5, 3), mar = c(2, 1, 1, 1))
2231
> 
2232
> plotRules(c(.1, .1, .9, .9, NA, .2, .2, .8, .8),
2233
+           c(.1, .9, .9, .1, NA, .2, .8, .8, .2),
2234
+           "Nested rectangles, both clockwise")
2235
> plotRules(c(.1, .1, .9, .9, NA, .2, .8, .8, .2),
2236
+           c(.1, .9, .9, .1, NA, .2, .2, .8, .8),
2237
+           "Nested rectangles, outer clockwise, inner anti-clockwise")
2238
> plotRules(c(.1, .1, .4, .4, NA, .6, .9, .9, .6),
2239
+           c(.1, .4, .4, .1, NA, .6, .6, .9, .9),
2240
+           "Disjoint rectangles")
2241
> plotRules(c(.1, .1, .6, .6, NA, .4, .4, .9, .9),
2242
+           c(.1, .6, .6, .1, NA, .4, .9, .9, .4),
2243
+           "Overlapping rectangles, both clockwise")
2244
> plotRules(c(.1, .1, .6, .6, NA, .4, .9, .9, .4),
2245
+           c(.1, .6, .6, .1, NA, .4, .4, .9, .9),
2246
+           "Overlapping rectangles, one clockwise, other anti-clockwise")
2247
> 
2248
> par(op)
2249
> 
2250
> 
2251
> 
2252
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2253
> cleanEx()
56927 ripley 2254
> nameEx("rasterImage")
2255
> ### * rasterImage
56353 ripley 2256
> 
2257
> flush(stderr()); flush(stdout())
2258
> 
2259
> ### Name: rasterImage
2260
> ### Title: Draw One or More Raster Images
2261
> ### Aliases: rasterImage
2262
> ### Keywords: aplot
2263
> 
2264
> ### ** Examples
2265
> 
2266
> require(grDevices)
2267
> ## set up the plot region:
2268
> op <- par(bg = "thistle")
61157 ripley 2269
> plot(c(100, 250), c(300, 450), type = "n", xlab = "", ylab = "")
2270
> image <- as.raster(matrix(0:1, ncol = 5, nrow = 3))
56353 ripley 2271
Warning in matrix(0:1, ncol = 5, nrow = 3) :
2272
  data length [2] is not a sub-multiple or multiple of the number of rows [3]
61157 ripley 2273
> rasterImage(image, 100, 300, 150, 350, interpolate = FALSE)
56353 ripley 2274
> rasterImage(image, 100, 400, 150, 450)
2275
> rasterImage(image, 200, 300, 200 + xinch(.5), 300 + yinch(.3),
61157 ripley 2276
+             interpolate = FALSE)
2277
> rasterImage(image, 200, 400, 250, 450, angle = 15, interpolate = FALSE)
56353 ripley 2278
> par(op)
2279
> 
2280
> 
2281
> 
2282
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2283
> cleanEx()
2284
> nameEx("rect")
2285
> ### * rect
2286
> 
2287
> flush(stderr()); flush(stdout())
2288
> 
2289
> ### Name: rect
2290
> ### Title: Draw One or More Rectangles
2291
> ### Aliases: rect
2292
> ### Keywords: aplot
2293
> 
2294
> ### ** Examples
2295
> 
2296
> require(grDevices)
2297
> ## set up the plot region:
2298
> op <- par(bg = "thistle")
61157 ripley 2299
> plot(c(100, 250), c(300, 450), type = "n", xlab = "", ylab = "",
56353 ripley 2300
+      main = "2 x 11 rectangles; 'rect(100+i,300+i,  150+i,380+i)'")
2301
> i <- 4*(0:10)
2302
> ## draw rectangles with bottom left (100, 300)+i
2303
> ## and top right (150, 380)+i
61169 ripley 2304
> rect(100+i, 300+i, 150+i, 380+i, col = rainbow(11, start = 0.7, end = 0.1))
61157 ripley 2305
> rect(240-i, 320+i, 250-i, 410+i, col = heat.colors(11), lwd = i/5)
56353 ripley 2306
> ## Background alternating  ( transparent / "bg" ) :
2307
> j <- 10*(0:5)
2308
> rect(125+j, 360+j,   141+j, 405+j/2, col = c(NA,0),
2309
+      border = "gold", lwd = 2)
2310
> rect(125+j, 296+j/2, 141+j, 331+j/5, col = c(NA,"midnightblue"))
2311
> mtext("+  2 x 6 rect(*, col = c(NA,0)) and  col = c(NA,\"m..blue\"))")
2312
> 
2313
> ## an example showing colouring and shading
61157 ripley 2314
> plot(c(100, 200), c(300, 450), type= "n", xlab = "", ylab = "")
56353 ripley 2315
> rect(100, 300, 125, 350) # transparent
61157 ripley 2316
> rect(100, 400, 125, 450, col = "green", border = "blue") # coloured
2317
> rect(115, 375, 150, 425, col = par("bg"), border = "transparent")
2318
> rect(150, 300, 175, 350, density = 10, border = "red")
2319
> rect(150, 400, 175, 450, density = 30, col = "blue",
2320
+      angle = -30, border = "transparent")
56353 ripley 2321
> 
61157 ripley 2322
> legend(180, 450, legend = 1:4, fill = c(NA, "green", par("fg"), "blue"),
2323
+        density = c(NA, NA, 10, 30), angle = c(NA, NA, 30, -30))
56353 ripley 2324
> 
2325
> par(op)
2326
> 
2327
> 
2328
> 
2329
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2330
> cleanEx()
2331
> nameEx("rug")
2332
> ### * rug
2333
> 
2334
> flush(stderr()); flush(stdout())
2335
> 
2336
> ### Name: rug
2337
> ### Title: Add a Rug to a Plot
2338
> ### Aliases: rug
2339
> ### Keywords: aplot
2340
> 
2341
> ### ** Examples
2342
> 
61169 ripley 2343
> require(stats)  # both 'density' and its default method
56353 ripley 2344
> with(faithful, {
2345
+     plot(density(eruptions, bw = 0.15))
2346
+     rug(eruptions)
2347
+     rug(jitter(eruptions, amount = 0.01), side = 3, col = "light blue")
2348
+ })
2349
> 
2350
> 
2351
> 
2352
> cleanEx()
2353
> nameEx("screen")
2354
> ### * screen
2355
> 
2356
> flush(stderr()); flush(stdout())
2357
> 
2358
> ### Name: screen
2359
> ### Title: Creating and Controlling Multiple Screens on a Single Device
2360
> ### Aliases: screen split.screen erase.screen close.screen
2361
> ### Keywords: aplot dplot device
2362
> 
2363
> ### ** Examples
2364
> 
2365
> if (interactive()) {
2366
+ par(bg = "white")           # default is likely to be transparent
61169 ripley 2367
+ split.screen(c(2, 1))       # split display into two screens
2368
+ split.screen(c(1, 3), screen = 2) # now split the bottom half into 3
56353 ripley 2369
+ screen(1) # prepare screen 1 for output
2370
+ plot(10:1)
2371
+ screen(4) # prepare screen 4 for output
2372
+ plot(10:1)
2373
+ close.screen(all = TRUE)    # exit split-screen mode
2374
+ 
61169 ripley 2375
+ split.screen(c(2, 1))       # split display into two screens
2376
+ split.screen(c(1, 2), 2)    # split bottom half in two
56353 ripley 2377
+ plot(1:10)                  # screen 3 is active, draw plot
2378
+ erase.screen()              # forgot label, erase and redraw
61157 ripley 2379
+ plot(1:10, ylab = "ylab 3")
56353 ripley 2380
+ screen(1)                   # prepare screen 1 for output
2381
+ plot(1:10)
2382
+ screen(4)                   # prepare screen 4 for output
61157 ripley 2383
+ plot(1:10, ylab = "ylab 4")
56353 ripley 2384
+ screen(1, FALSE)            # return to screen 1, but do not clear
61157 ripley 2385
+ plot(10:1, axes = FALSE, lty = 2, ylab = "")  # overlay second plot
56353 ripley 2386
+ axis(4)                     # add tic marks to right-hand axis
2387
+ title("Plot 1")
2388
+ close.screen(all = TRUE)    # exit split-screen mode
2389
+ }
2390
> 
2391
> 
2392
> 
2393
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2394
> cleanEx()
2395
> nameEx("segments")
2396
> ### * segments
2397
> 
2398
> flush(stderr()); flush(stdout())
2399
> 
2400
> ### Name: segments
2401
> ### Title: Add Line Segments to a Plot
2402
> ### Aliases: segments
2403
> ### Keywords: aplot
2404
> 
2405
> ### ** Examples
2406
> 
2407
> x <- stats::runif(12); y <- stats::rnorm(12)
61169 ripley 2408
> i <- order(x, y); x <- x[i]; y <- y[i]
61157 ripley 2409
> plot(x, y, main = "arrows(.) and segments(.)")
56353 ripley 2410
> ## draw arrows from point to point :
61169 ripley 2411
> s <- seq(length(x)-1)  # one shorter than data
56353 ripley 2412
> arrows(x[s], y[s], x[s+1], y[s+1], col= 1:3)
2413
> s <- s[-length(s)]
2414
> segments(x[s], y[s], x[s+2], y[s+2], col= 'pink')
2415
> 
2416
> 
2417
> 
2418
> cleanEx()
2419
> nameEx("smoothScatter")
2420
> ### * smoothScatter
2421
> 
2422
> flush(stderr()); flush(stdout())
2423
> 
2424
> ### Name: smoothScatter
2425
> ### Title: Scatterplots with Smoothed Densities Color Representation
2426
> ### Aliases: smoothScatter
2427
> ### Keywords: hplot
2428
> 
2429
> ### ** Examples
2430
> 
61169 ripley 2431
> ## A largish data set
2432
> n <- 10000
2433
> x1  <- matrix(rnorm(n), ncol = 2)
2434
> x2  <- matrix(rnorm(n, mean = 3, sd = 1.5), ncol = 2)
2435
> x   <- rbind(x1, x2)
56353 ripley 2436
> 
61169 ripley 2437
> oldpar <- par(mfrow = c(2, 2))
2438
> smoothScatter(x, nrpoints = 0)
56353 ripley 2439
KernSmooth 2.23 loaded
2440
Copyright M. P. Wand 1997-2009
61169 ripley 2441
> smoothScatter(x)
56353 ripley 2442
> 
61169 ripley 2443
> ## a different color scheme:
2444
> Lab.palette <- colorRampPalette(c("blue", "orange", "red"), space = "Lab")
2445
> smoothScatter(x, colramp = Lab.palette)
56353 ripley 2446
> 
61169 ripley 2447
> ## somewhat similar, using identical smoothing computations,
2448
> ## but considerably *less* efficient for really large data:
2449
> plot(x, col = densCols(x), pch = 20)
56353 ripley 2450
> 
61169 ripley 2451
> ## use with pairs:
2452
> par(mfrow = c(1, 1))
2453
> y <- matrix(rnorm(40000), ncol = 4) + 3*rnorm(10000)
2454
> y[, c(2,4)] <-  -y[, c(2,4)]
2455
> pairs(y, panel = function(...) smoothScatter(..., nrpoints = 0, add = TRUE))
56353 ripley 2456
> 
61169 ripley 2457
> par(oldpar)
56353 ripley 2458
> 
2459
> 
2460
> 
2461
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2462
> cleanEx()
2463
> nameEx("spineplot")
2464
> ### * spineplot
2465
> 
2466
> flush(stderr()); flush(stdout())
2467
> 
2468
> ### Name: spineplot
2469
> ### Title: Spine Plots and Spinograms
2470
> ### Aliases: spineplot spineplot.default spineplot.formula
2471
> ### Keywords: hplot
2472
> 
2473
> ### ** Examples
2474
> 
2475
> ## treatment and improvement of patients with rheumatoid arthritis
2476
> treatment <- factor(rep(c(1, 2), c(43, 41)), levels = c(1, 2),
2477
+                     labels = c("placebo", "treated"))
2478
> improved <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
2479
+                    levels = c(1, 2, 3),
2480
+                    labels = c("none", "some", "marked"))
2481
> 
2482
> ## (dependence on a categorical variable)
2483
> (spineplot(improved ~ treatment))
2484
         improved
2485
treatment none some marked
2486
  placebo   29    7      7
2487
  treated   13    7     21
2488
> 
2489
> ## applications and admissions by department at UC Berkeley
2490
> ## (two-way tables)
2491
> (spineplot(margin.table(UCBAdmissions, c(3, 2)),
2492
+            main = "Applications at UCB"))
2493
    Gender
2494
Dept Male Female
2495
   A  825    108
2496
   B  560     25
2497
   C  325    593
2498
   D  417    375
2499
   E  191    393
2500
   F  373    341
2501
> (spineplot(margin.table(UCBAdmissions, c(3, 1)),
2502
+            main = "Admissions at UCB"))
2503
    Admit
2504
Dept Admitted Rejected
2505
   A      601      332
2506
   B      370      215
2507
   C      322      596
2508
   D      269      523
2509
   E      147      437
2510
   F       46      668
2511
> 
2512
> ## NASA space shuttle o-ring failures
2513
> fail <- factor(c(2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1,
2514
+                  1, 1, 1, 2, 1, 1, 1, 1, 1),
2515
+                levels = c(1, 2), labels = c("no", "yes"))
2516
> temperature <- c(53, 57, 58, 63, 66, 67, 67, 67, 68, 69, 70, 70,
2517
+                  70, 70, 72, 73, 75, 75, 76, 76, 78, 79, 81)
2518
> 
2519
> ## (dependence on a numerical variable)
2520
> (spineplot(fail ~ temperature))
2521
           fail
2522
temperature no yes
2523
    [50,55]  0   1
2524
    (55,60]  0   2
2525
    (60,65]  0   1
2526
    (65,70]  8   2
2527
    (70,75]  3   1
2528
    (75,80]  4   0
2529
    (80,85]  1   0
2530
> (spineplot(fail ~ temperature, breaks = 3))
2531
           fail
2532
temperature no yes
2533
    [50,60]  0   3
2534
    (60,70]  8   3
2535
    (70,80]  7   1
2536
    (80,90]  1   0
2537
> (spineplot(fail ~ temperature, breaks = quantile(temperature)))
2538
           fail
2539
temperature no yes
2540
    [53,67]  4   4
2541
    (67,70]  4   2
2542
    (70,75]  3   1
2543
    (75,81]  5   0
2544
> 
2545
> ## highlighting for failures
2546
> spineplot(fail ~ temperature, ylevels = 2:1)
2547
> 
2548
> 
2549
> 
2550
> cleanEx()
2551
> nameEx("stars")
2552
> ### * stars
2553
> 
2554
> flush(stderr()); flush(stdout())
2555
> 
2556
> ### Name: stars
2557
> ### Title: Star (Spider/Radar) Plots and Segment Diagrams
2558
> ### Aliases: stars
2559
> ### Keywords: hplot multivariate
2560
> 
2561
> ### ** Examples
2562
> 
2563
> require(grDevices)
2564
> stars(mtcars[, 1:7], key.loc = c(14, 2),
2565
+       main = "Motor Trend Cars : stars(*, full = F)", full = FALSE)
2566
> stars(mtcars[, 1:7], key.loc = c(14, 1.5),
61157 ripley 2567
+       main = "Motor Trend Cars : full stars()", flip.labels = FALSE)
56353 ripley 2568
> 
2569
> ## 'Spider' or 'Radar' plot:
61169 ripley 2570
> stars(mtcars[, 1:7], locations = c(0, 0), radius = FALSE,
2571
+       key.loc = c(0, 0), main = "Motor Trend Cars", lty = 2)
56353 ripley 2572
> 
2573
> ## Segment Diagrams:
2574
> palette(rainbow(12, s = 0.6, v = 0.75))
2575
> stars(mtcars[, 1:7], len = 0.8, key.loc = c(12, 1.5),
2576
+       main = "Motor Trend Cars", draw.segments = TRUE)
2577
> stars(mtcars[, 1:7], len = 0.6, key.loc = c(1.5, 0),
2578
+       main = "Motor Trend Cars", draw.segments = TRUE,
61157 ripley 2579
+       frame.plot = TRUE, nrow = 4, cex = .7)
56353 ripley 2580
> 
2581
> ## scale linearly (not affinely) to [0, 1]
2582
> USJudge <- apply(USJudgeRatings, 2, function(x) x/max(x))
2583
> Jnam <- row.names(USJudgeRatings)
61169 ripley 2584
> Snam <- abbreviate(substring(Jnam, 1, regexpr("[,.]",Jnam) - 1), 7)
56353 ripley 2585
> stars(USJudge, labels = Jnam, scale = FALSE,
2586
+       key.loc = c(13, 1.5), main = "Judge not ...", len = 0.8)
2587
> stars(USJudge, labels = Snam, scale = FALSE,
2588
+       key.loc = c(13, 1.5), radius = FALSE)
2589
> 
2590
> loc <- stars(USJudge, labels = NULL, scale = FALSE,
2591
+              radius = FALSE, frame.plot = TRUE,
2592
+              key.loc = c(13, 1.5), main = "Judge not ...", len = 1.2)
2593
> text(loc, Snam, col = "blue", cex = 0.8, xpd = TRUE)
2594
> 
2595
> ## 'Segments':
2596
> stars(USJudge, draw.segments = TRUE, scale = FALSE, key.loc = c(13,1.5))
2597
> 
2598
> ## 'Spider':
61169 ripley 2599
> stars(USJudgeRatings, locations = c(0, 0), scale = FALSE, radius  =  FALSE,
2600
+       col.stars = 1:10, key.loc = c(0, 0), main = "US Judges rated")
56747 maechler 2601
> ## Same as above, but with colored lines instead of filled polygons.
61169 ripley 2602
> stars(USJudgeRatings, locations = c(0, 0), scale = FALSE, radius  =  FALSE,
2603
+       col.lines = 1:10, key.loc = c(0, 0), main = "US Judges rated")
56353 ripley 2604
> ## 'Radar-Segments'
61157 ripley 2605
> stars(USJudgeRatings[1:10,], locations = 0:1, scale = FALSE,
2606
+       draw.segments = TRUE, col.segments = 0, col.stars = 1:10, key.loc =  0:1,
2607
+       main = "US Judges 1-10 ")
56353 ripley 2608
> palette("default")
61169 ripley 2609
> stars(cbind(1:16, 10*(16:1)), draw.segments = TRUE,
56353 ripley 2610
+       main = "A Joke -- do *not* use symbols on 2D data!")
2611
> 
2612
> 
2613
> 
2614
> cleanEx()
2615
> nameEx("stem")
2616
> ### * stem
2617
> 
2618
> flush(stderr()); flush(stdout())
2619
> 
2620
> ### Name: stem
2621
> ### Title: Stem-and-Leaf Plots
2622
> ### Aliases: stem
2623
> ### Keywords: univar distribution
2624
> 
2625
> ### ** Examples
2626
> 
2627
> stem(islands)
2628
 
2629
  The decimal point is 3 digit(s) to the right of the |
2630
 
2631
 
2632
   2 | 07
2633
   4 | 5
2634
   6 | 8
2635
   8 | 4
2636
  10 | 5
2637
  12 | 
2638
  14 | 
2639
  16 | 0
2640
 
2641
> stem(log10(islands))
2642
 
2643
  The decimal point is at the |
2644
 
2645
  1 | 1111112222233444
2646
  1 | 5555556666667899999
2647
  2 | 3344
2648
  2 | 59
2649
  3 | 
2650
  3 | 5678
2651
  4 | 012
2652
 
2653
> 
2654
> 
2655
> 
2656
> cleanEx()
2657
> nameEx("stripchart")
2658
> ### * stripchart
2659
> 
2660
> flush(stderr()); flush(stdout())
2661
> 
2662
> ### Name: stripchart
2663
> ### Title: 1-D Scatter Plots
2664
> ### Aliases: stripchart stripchart.default stripchart.formula
2665
> ### Keywords: hplot
2666
> 
2667
> ### ** Examples
2668
> 
2669
> x <- stats::rnorm(50)
2670
> xr <- round(x, 1)
2671
> stripchart(x) ; m <- mean(par("usr")[1:2])
2672
> text(m, 1.04, "stripchart(x, \"overplot\")")
2673
> stripchart(xr, method = "stack", add = TRUE, at = 1.2)
2674
> text(m, 1.35, "stripchart(round(x,1), \"stack\")")
2675
> stripchart(xr, method = "jitter", add = TRUE, at = 0.7)
2676
> text(m, 0.85, "stripchart(round(x,1), \"jitter\")")
2677
> 
2678
> stripchart(decrease ~ treatment,
61431 ripley 2679
+     main = "stripchart(OrchardSprays)",
56353 ripley 2680
+     vertical = TRUE, log = "y", data = OrchardSprays)
2681
> 
2682
> stripchart(decrease ~ treatment, at = c(1:8)^2,
61431 ripley 2683
+     main = "stripchart(OrchardSprays)",
56353 ripley 2684
+     vertical = TRUE, log = "y", data = OrchardSprays)
2685
> 
2686
> 
2687
> 
2688
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2689
> cleanEx()
2690
> nameEx("strwidth")
2691
> ### * strwidth
2692
> 
2693
> flush(stderr()); flush(stdout())
2694
> 
2695
> ### Name: strwidth
2696
> ### Title: Plotting Dimensions of Character Strings and Math Expressions
2697
> ### Aliases: strwidth strheight
2698
> ### Keywords: dplot character
2699
> 
2700
> ### ** Examples
2701
> 
2702
> str.ex <- c("W","w","I",".","WwI.")
61169 ripley 2703
> op <- par(pty = "s"); plot(1:100, 1:100, type = "n")
56353 ripley 2704
> sw <- strwidth(str.ex); sw
2705
[1] 3.2600930 2.4934186 0.9600698 0.9600698 7.6736512
2706
> all.equal(sum(sw[1:4]), sw[5])
2707
[1] TRUE
2708
> #- since the last string contains the others
2709
> 
61169 ripley 2710
> sw.i <- strwidth(str.ex, "inches"); 25.4 * sw.i  # width in [mm]
56353 ripley 2711
[1] 3.996267 3.056467 1.176867 1.176867 9.406467
2712
> unique(sw / sw.i)
2713
[1] 20.72093 20.72093
2714
> # constant factor: 1 value
61169 ripley 2715
> mean(sw.i / strwidth(str.ex, "fig")) / par('fin')[1]  # = 1: are the same
56353 ripley 2716
[1] 1
2717
> 
2718
> ## See how letters fall in classes
2719
> ##  -- depending on graphics device and font!
2720
> all.lett <- c(letters, LETTERS)
61169 ripley 2721
> shL <- strheight(all.lett, units = "inches") * 72  # 'big points'
2722
> table(shL)  # all have same heights ...
56353 ripley 2723
shL
2724
8.616 
2725
   52 
2726
> mean(shL)/par("cin")[2] # around 0.6
2727
[1] 43.08
2728
> 
61169 ripley 2729
> (swL <- strwidth(all.lett, units = "inches") * 72)  # 'big points'
56353 ripley 2730
 [1]  6.672  6.672  6.000  6.672  6.672  3.336  6.672  6.672  2.664  2.664
2731
[11]  6.000  2.664  9.996  6.672  6.672  6.672  6.672  3.996  6.000  3.336
2732
[21]  6.672  6.000  8.664  6.000  6.000  6.000  8.004  8.004  8.664  8.664
2733
[31]  8.004  7.332  9.336  8.664  3.336  6.000  8.004  6.672  9.996  8.664
2734
[41]  9.336  8.004  9.336  8.664  8.004  7.332  8.664  8.004 11.328  8.004
2735
[51]  8.004  7.332
2736
> split(all.lett, factor(round(swL, 2)))
2737
$`2.66`
2738
[1] "i" "j" "l"
2739
 
2740
$`3.34`
2741
[1] "f" "t" "I"
2742
 
2743
$`4`
2744
[1] "r"
2745
 
2746
$`6`
2747
[1] "c" "k" "s" "v" "x" "y" "z" "J"
2748
 
2749
$`6.67`
2750
 [1] "a" "b" "d" "e" "g" "h" "n" "o" "p" "q" "u" "L"
2751
 
2752
$`7.33`
2753
[1] "F" "T" "Z"
2754
 
2755
$`8`
2756
[1] "A" "B" "E" "K" "P" "S" "V" "X" "Y"
2757
 
2758
$`8.66`
2759
[1] "w" "C" "D" "H" "N" "R" "U"
2760
 
2761
$`9.34`
2762
[1] "G" "O" "Q"
2763
 
2764
$`10`
2765
[1] "m" "M"
2766
 
2767
$`11.33`
2768
[1] "W"
2769
 
2770
> 
2771
> sumex <- expression(sum(x[i], i=1,n), e^{i * pi} == -1)
2772
> strwidth(sumex)
2773
[1]  5.795241 11.484959
2774
> strheight(sumex)
2775
[1] 8.057449 3.420738
2776
> 
61169 ripley 2777
> par(op)  #- reset to previous setting
56353 ripley 2778
> 
2779
> 
2780
> 
2781
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
2782
> cleanEx()
2783
> nameEx("sunflowerplot")
2784
> ### * sunflowerplot
2785
> 
2786
> flush(stderr()); flush(stdout())
2787
> 
2788
> ### Name: sunflowerplot
2789
> ### Title: Produce a Sunflower Scatter Plot
2790
> ### Aliases: sunflowerplot sunflowerplot.default sunflowerplot.formula
2791
> ### Keywords: hplot smooth nonparametric
2792
> 
2793
> ### ** Examples
2794
> 
2795
> require(stats)
2796
> require(grDevices)
2797
> 
2798
> ## 'number' is computed automatically:
2799
> sunflowerplot(iris[, 3:4])
2800
> ## Imitating  Chambers et al., p.109, closely:
61157 ripley 2801
> sunflowerplot(iris[, 3:4], cex = .2, cex.fact = 1, size = .035, seg.lwd = .8)
56353 ripley 2802
> ## or
61157 ripley 2803
> sunflowerplot(Petal.Width ~ Petal.Length, data = iris,
2804
+               cex = .2, cex.fact = 1, size = .035, seg.lwd = .8)
56353 ripley 2805
> 
2806
> 
61169 ripley 2807
> sunflowerplot(x = sort(2*round(rnorm(100))), y = round(rnorm(100), 0),
56353 ripley 2808
+               main = "Sunflower Plot of Rounded N(0,1)")
2809
> ## Similarly using a "xyTable" argument:
61169 ripley 2810
> xyT <- xyTable(x = sort(2*round(rnorm(100))), y = round(rnorm(100), 0),
61157 ripley 2811
+                digits = 3)
2812
> utils::str(xyT, vec.len = 20)
56353 ripley 2813
List of 3
2814
 $ x     : num [1:25] -6 -4 -4 -4 -4 -2 -2 -2 -2 -2 0 0 0 0 0 0 2 2 2 2 2 4 4 4 4
2815
 $ y     : num [1:25] 0 -2 0 1 2 -2 -1 0 1 2 -3 -2 -1 0 1 2 -2 -1 0 1 3 -1 0 1 2
2816
 $ number: int [1:25] 1 1 1 1 3 1 4 8 4 1 1 3 5 17 12 2 1 8 12 6 1 1 3 2 1
2817
> sunflowerplot(xyT, main = "2nd Sunflower Plot of Rounded N(0,1)")
2818
> 
2819
> ## A 'marked point process' {explicit 'number' argument}:
61169 ripley 2820
> sunflowerplot(rnorm(100), rnorm(100), number = rpois(n = 100, lambda = 2),
61157 ripley 2821
+               main = "Sunflower plot (marked point process)",
2822
+               rotate = TRUE, col = "blue4")
56353 ripley 2823
> 
2824
> 
2825
> 
2826
> cleanEx()
2827
> nameEx("symbols")
2828
> ### * symbols
2829
> 
2830
> flush(stderr()); flush(stdout())
2831
> 
2832
> ### Name: symbols
2833
> ### Title: Draw Symbols (Circles, Squares, Stars, Thermometers, Boxplots)
2834
> ### Aliases: symbols
2835
> ### Keywords: aplot hplot multivariate
2836
> 
2837
> ### ** Examples
2838
> 
2839
> require(stats); require(grDevices)
2840
> x <- 1:10
2841
> y <- sort(10*runif(10))
2842
> z <- runif(10)
2843
> z3 <- cbind(z, 2*runif(10), runif(10))
2844
> symbols(x, y, thermometers = cbind(.5, 1, z), inches = .5, fg = 1:10)
2845
> symbols(x, y, thermometers = z3, inches = FALSE)
61169 ripley 2846
> text(x, y, apply(format(round(z3, digits = 2)), 1, paste, collapse = ","),
56353 ripley 2847
+      adj = c(-.2,0), cex = .75, col = "purple", xpd = NA)
2848
> 
2849
> ## Note that  example(trees)  shows more sensible plots!
2850
> N <- nrow(trees)
2851
> with(trees, {
2852
+ ## Girth is diameter in inches
2853
+ symbols(Height, Volume, circles = Girth/24, inches = FALSE,
2854
+         main = "Trees' Girth") # xlab and ylab automatically
2855
+ ## Colours too:
2856
+ op <- palette(rainbow(N, end = 0.9))
2857
+ symbols(Height, Volume, circles = Girth/16, inches = FALSE, bg = 1:N,
2858
+         fg = "gray30", main = "symbols(*, circles = Girth/16, bg = 1:N)")
2859
+ palette(op)
2860
+ })
2861
> 
2862
> 
2863
> 
2864
> cleanEx()
2865
> nameEx("title")
2866
> ### * title
2867
> 
2868
> flush(stderr()); flush(stdout())
2869
> 
2870
> ### Name: title
2871
> ### Title: Plot Annotation
2872
> ### Aliases: title
2873
> ### Keywords: aplot
2874
> 
2875
> ### ** Examples
2876
> 
2877
> plot(cars, main = "") # here, could use main directly
2878
> title(main = "Stopping Distance versus Speed")
2879
> 
2880
> plot(cars, main = "")
61157 ripley 2881
> title(main = list("Stopping Distance versus Speed", cex = 1.5,
2882
+                   col = "red", font = 3))
56353 ripley 2883
> 
2884
> ## Specifying "..." :
2885
> plot(1, col.axis = "sky blue", col.lab = "thistle")
2886
> title("Main Title", sub = "sub title",
2887
+       cex.main = 2,   font.main= 4, col.main= "blue",
2888
+       cex.sub = 0.75, font.sub = 3, col.sub = "red")
2889
> 
2890
> 
2891
> x <- seq(-4, 4, len = 101)
2892
> y <- cbind(sin(x), cos(x))
2893
> matplot(x, y, type = "l", xaxt = "n",
2894
+         main = expression(paste(plain(sin) * phi, "  and  ",
2895
+                                 plain(cos) * phi)),
2896
+         ylab = expression("sin" * phi, "cos" * phi), # only 1st is taken
2897
+         xlab = expression(paste("Phase Angle ", phi)),
2898
+         col.main = "blue")
2899
> axis(1, at = c(-pi, -pi/2, 0, pi/2, pi),
2900
+      labels = expression(-pi, -pi/2, 0, pi/2, pi))
2901
> abline(h = 0, v = pi/2 * c(-1,1), lty = 2, lwd = .1, col = "gray70")
2902
> 
2903
> 
2904
> 
2905
> cleanEx()
2906
> nameEx("units")
2907
> ### * units
2908
> 
2909
> flush(stderr()); flush(stdout())
2910
> 
2911
> ### Name: units
2912
> ### Title: Graphical Units
2913
> ### Aliases: xinch yinch xyinch
2914
> ### Keywords: dplot
2915
> 
2916
> ### ** Examples
2917
> 
61169 ripley 2918
> all(c(xinch(), yinch()) == xyinch()) # TRUE
56353 ripley 2919
[1] TRUE
2920
> xyinch()
2921
[1] 1.5000000 0.4185559
2922
> xyinch #- to see that is really   delta{"usr"} / "pin"
2923
function (xy = 1, warn.log = TRUE) 
2924
{
2925
    if (warn.log && (par("xlog") || par("ylog"))) 
60841 ripley 2926
        warning("log scale:  xyinch() is nonsense")
56353 ripley 2927
    u <- par("usr")
2928
    xy * c(u[2L] - u[1L], u[4L] - u[3L])/par("pin")
2929
}
63202 ripley 2930
<bytecode: 0x2cda550>
56353 ripley 2931
<environment: namespace:graphics>
2932
> 
2933
> ## plot labels offset 0.12 inches to the right
2934
> ## of plotted symbols in a plot
2935
> with(mtcars, {
61157 ripley 2936
+     plot(mpg, disp, pch = 19, main = "Motor Trend Cars")
56353 ripley 2937
+     text(mpg + xinch(0.12), disp, row.names(mtcars),
61169 ripley 2938
+          adj = 0, cex = .7, col = "blue")
56353 ripley 2939
+     })
2940
> 
2941
> 
2942
> 
2943
> cleanEx()
2944
> nameEx("xspline")
2945
> ### * xspline
2946
> 
2947
> flush(stderr()); flush(stdout())
2948
> 
2949
> ### Name: xspline
2950
> ### Title: Draw an X-spline
2951
> ### Aliases: xspline
2952
> ### Keywords: aplot
2953
> 
2954
> ### ** Examples
2955
> 
2956
> ## based on examples in ?grid.xspline
2957
> 
2958
> xsplineTest <- function(s, open = TRUE,
2959
+                         x = c(1,1,3,3)/4,
2960
+                         y = c(1,3,3,1)/4, ...) {
61157 ripley 2961
+     plot(c(0,1), c(0,1), type = "n", axes = FALSE, xlab = "", ylab = "")
2962
+     points(x, y, pch = 19)
56353 ripley 2963
+     xspline(x, y, s, open, ...)
2964
+     text(x+0.05*c(-1,-1,1,1), y+0.05*c(-1,1,1,-1), s)
2965
+ }
61157 ripley 2966
> op <- par(mfrow = c(3,3), mar = rep(0,4), oma = c(0,0,2,0))
56353 ripley 2967
> xsplineTest(c(0, -1, -1, 0))
2968
> xsplineTest(c(0, -1,  0, 0))
2969
> xsplineTest(c(0, -1,  1, 0))
2970
> xsplineTest(c(0,  0, -1, 0))
2971
> xsplineTest(c(0,  0,  0, 0))
2972
> xsplineTest(c(0,  0,  1, 0))
2973
> xsplineTest(c(0,  1, -1, 0))
2974
> xsplineTest(c(0,  1,  0, 0))
2975
> xsplineTest(c(0,  1,  1, 0))
61157 ripley 2976
> title("Open X-splines", outer = TRUE)
56353 ripley 2977
> 
61157 ripley 2978
> par(mfrow = c(3,3), mar = rep(0,4), oma = c(0,0,2,0))
2979
> xsplineTest(c(0, -1, -1, 0), FALSE, col = "grey80")
2980
> xsplineTest(c(0, -1,  0, 0), FALSE, col = "grey80")
2981
> xsplineTest(c(0, -1,  1, 0), FALSE, col = "grey80")
2982
> xsplineTest(c(0,  0, -1, 0), FALSE, col = "grey80")
2983
> xsplineTest(c(0,  0,  0, 0), FALSE, col = "grey80")
2984
> xsplineTest(c(0,  0,  1, 0), FALSE, col = "grey80")
2985
> xsplineTest(c(0,  1, -1, 0), FALSE, col = "grey80")
2986
> xsplineTest(c(0,  1,  0, 0), FALSE, col = "grey80")
2987
> xsplineTest(c(0,  1,  1, 0), FALSE, col = "grey80")
2988
> title("Closed X-splines", outer = TRUE)
56353 ripley 2989
> 
2990
> par(op)
2991
> 
2992
> x <- sort(stats::rnorm(5))
2993
> y <- sort(stats::rnorm(5))
61157 ripley 2994
> plot(x, y, pch = 19)
2995
> res <- xspline(x, y, 1, draw = FALSE)
56353 ripley 2996
> lines(res)
2997
> ## the end points may be very close together,
2998
> ## so use last few for direction
2999
> nr <- length(res$x)
61157 ripley 3000
> arrows(res$x[1], res$y[1], res$x[4], res$y[4], code = 1, length = 0.1)
3001
> arrows(res$x[nr-3], res$y[nr-3], res$x[nr], res$y[nr], code = 2, length = 0.1)
56353 ripley 3002
> 
3003
> 
3004
> 
3005
> graphics::par(get("par.postscript", pos = 'CheckExEnv'))
3006
> ### * <FOOTER>
3007
> ###
62439 ripley 3008
> options(digits = 7L)
61787 ripley 3009
> base::cat("Time elapsed: ", proc.time() - base::get("ptime", pos = 'CheckExEnv'),"\n")
63202 ripley 3010
Time elapsed:  3.278 0.059 3.347 0 0 
56353 ripley 3011
> grDevices::dev.off()
3012
null device 
3013
          1 
3014
> ###
3015
> ### Local variables: ***
3016
> ### mode: outline-minor ***
3017
> ### outline-regexp: "\\(> \\)?### [*]+" ***
3018
> ### End: ***
3019
> quit('no')