The R Project SVN R

Rev

Rev 89794 | Details | Compare with Previous | Last modification | View Log | RSS feed

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