File: plot.R

package info (click to toggle)
futilities 270.73-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 804 kB
  • ctags: 5
  • sloc: makefile: 13
file content (477 lines) | stat: -rw-r--r-- 12,826 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received A copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA

# Copyrights (C)
# for this R-port:
#   1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL
#   Diethelm Wuertz <wuertz@itp.phys.ethz.ch>
#   www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
#   see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
#   see Rmetrics's copyright file


################################################################################
# FUNCTION:                 INTERNAL USED PLOT FUNCTIONS:
#  .residualsPlot            Returns a residual series plot
#  .acfPlot                  Returns a autocorrelation function plot
#  .pacfPlot                 Returns a partial ACF plot
#  .mrlPlot                  Returns a mean residual life plot
# FUNCTION:                 INTERNAL USED BIVARIATE PLOT FUNCTIONS:
#  .responsesPlot            Returns a response series plot
#  .firePlot                 Returns a fitted values vs.residuals plot
# FUNCTION:                 INTERNAL THREE-DIMENSIONAL PLOT UTILITIES:
#  .circlesPlot              Returns a circles plot indexing 3rd variable
#  .perspPlot                Returns a perspective plot in 2 dimensions
#  .contourPlot              Returns a contour plot in 2 dimensions
#  .histStack                Returns a stacked histogram plot
################################################################################


################################################################################
#  .residualsPlot            Returns a residual series plot
#  .acfPlot                  Returns a autocorrelation function plot
#  .pacfPlot                 Returns a partial ACF plot
#  .mrlPlot                  Returns a mean residual life plot


.residualsPlot <- 
    function(x, ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns time series graph of residuals

    # Arguments:
    #   x - an univariate time series of residuals

    # FUNCTION:

    # Get Data:
    x = as.vector(x)

    # Plot:
    plot(x, type = "l", ylab = "Residuals",
        main = "Residual Series", col = "steelblue", ...)
    rug(x, ticksize = 0.01, side = 4)
    grid()
    abline(h = 0, col = "grey")

    # Return Value:
    invisible()
}


# ------------------------------------------------------------------------------


.acfPlot <- 
    function(x, ...)
{
    # A function implemented by Diethelm Wuertz
    
    # FUNCTION:

    # Convert Type:
    x = as.vector(x)

    # ACF:
    acf(x, ...)

    # Return Value:
    invisible()
}


# ------------------------------------------------------------------------------


.pacfPlot <- 
    function(x, ...)
{
    # A function implemented by Diethelm Wuertz
    
    # FUNCTION:

    # Convert Type:
    x = as.vector(x)

    # ACF:
    pacf(x, ...)

    # Return Value:
    invisible()
}


# ------------------------------------------------------------------------------


.mrlPlot <- 
    function(x, ci = 0.95, umin = mean(x), umax = max(x), nint = 100,
    doplot = TRUE, plottype = c("autoscale", ""), labels = TRUE, ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Create a mean residual life plot with
    #   confidence intervals.

    # References:
    #   A function originally written by S. Coles

    # FUNCTION:

    # Convert Type:
    x = as.vector(x)

    # Settings:
    plottype = plottype[1]

    # Convert x to a vector, if the input is a data.frame.
    if (is.data.frame(x)) x = x[,1]
    sx = xu = xl = rep(NA, nint)
    u = seq(umin, umax, length = nint)
    for (i in 1:nint) {
        x = x[x >= u[i]]
        sx[i] = mean(x - u[i])
        sdev = sqrt(var(x))
        n = length(x)
        xu[i] = sx[i] + (qnorm((1 + ci)/2) * sdev) / sqrt(n)
        xl[i] = sx[i] - (qnorm((1 + ci)/2) * sdev) / sqrt(n)
    }

    # Plot:
    if (doplot) {
        if (labels) {
            xlab = "Threshold: u"
            ylab = "Mean Excess: e"
            main = "Mean Residual Live Plot"
        } else {
            main = xlab = ylab = ""
        }
        if (plottype == "autoscale") {
            ylim = c(min(xl[!is.na(xl)]), max(xu[!is.na(xu)]))
            plot(u, sx, type = "o", pch = 19, col = "steelblue",
                xlab = xlab, ylab = ylab, ylim = ylim, main = main, ...)
        } else {
            plot(u[!is.na(xl)], sx[!is.na(xl)], type = "o",
                pch = 19, col = "steelblue",
                xlab = xlab, ylab = ylab, main = main, ...)
        }
        lines(u[!is.na(xl)], xl[!is.na(xl)], col = "brown")
        lines(u[!is.na(xu)], xu[!is.na(xu)], col = "brown")
        if (labels) {
            grid()
            text = paste("ci =", as.character(round(ci, 3)))
            mtext(text, side = 4, adj = 0, cex = 0.7)
        }
    }

    # Result
    result = data.frame(threshold = u, mrl = sx)

    # Return Value:
    if (doplot) return(invisible(result)) else return(result)
}


################################################################################
#  .responsesPlot            Returns a response series plot
#  .firePlot                 Returns a fitted values vs.residuals plot


.responsesPlot <- 
    function(x, y = NULL, ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns time series graph of responses and fitted values

    # Arguments:
    #   x - an univariate time series of responses
    #   y - an univariate time series of fitted values

    # FUNCTION:

    # Get Data:
    x = as.vector(x)
    y = as.vector(y)

    # Responses Plot:
    plot(x, type = "l", ylab = "Responses",
        main = "Responses & Fitted Values", col = "steelblue", ...)
    rug(x, ticksize = 0.01, side = 4)
    grid()
    abline(h = 0, col = "grey")

    # Add fitted values:
    if (!is.null(y)) points(y, pch = 19, col = "red")

    # Return Value:
    invisible()
}


# ------------------------------------------------------------------------------


.firePlot <- 
    function(x, y, method = c("scatter", "hist"), ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns fitted values vs. residuals plots

    # Arguments:
    #   x - univariate time series (residuals)
    #   y - univariate time series (fitted)

    # FUNCTION:

    # Check Arguments:
    method = match.arg(method)

    # Get Data:
    x = as.vector(x)
    y = as.vector(y)


    if (method == "scatter") {

        # Scatter Plot:
        plot(x, y,
            xlab = "Fitted Values", ylab = "Residuals",
            main = "Residuals vs Fitted",
            pch = 19, col = "steelblue")
        panel.smooth(x, y)
        abline(h = 0, lty = 3, col = "grey")
        rug(x, ticksize = 0.01, side = 3)
        rug(y, ticksize = 0.01, side = 4)

    } else if (method == "hist") {

        # Histogram Plot:

        # Save default, for resetting ...
        def.par = par(no.readonly = TRUE)

        # Layout:
        nf = layout(matrix(c(2, 0, 1, 3), 2, 2, byrow = TRUE), c(3, 1),
            c(1, 3), TRUE)

        # Scatterplot:
        par(mar = c(3 ,3, 1, 1))
        plot(x, y, xlim = range(x), ylim = range(y),
            xlab = "", ylab = "", pch = 19, col = "steelblue")
        panel.smooth(x, y)
        abline(h = 0, lty = 3, col = "grey")
        rug(x, side = 3)
        rug(y, side = 4)

        # Histogram:
        xhist = hist(x, nclass = 15, plot = FALSE)
        yhist = hist(y, nclass = 15, plot = FALSE)
        top = max(c(xhist$counts, yhist$counts))

        # X-Side:
        par(mar = c(0, 3, 1, 1))
        Main = "\n                            Fitted"
        barplot(xhist$counts, axes = FALSE, ylim = c(0, top),
            space = 0, col = "steelblue", border = "white",
            main = Main)
        abline(h = 0, lwd = 2, col = "grey")

        # Y-Side:
        par(mar = c(3, 0, 1, 1))
        barplot(yhist$counts, axes = FALSE, xlim = c(0, top),
            space = 0, col = "steelblue", , border = "white",
            horiz = TRUE, main = "Residuals")
        abline(v = 0, lwd = 2, col = "grey")

        # Reset:
        par(def.par)

    }

    # Return Value:
    invisible()
}


################################################################################
#  .circlesPlot           Returns a scatterplot of circles indexing 3rd variable
#  .perspPlot             Returns a perspective plot in 2 dimensions
#  .contourPlot           Returns a contour plot in 2 dimensions
#  .histStack             Returns a stacked histogram plot


.circlesPlot <- 
    function(x, y = NULL, z = NULL, scale = 1, points = TRUE,
    labels = TRUE, ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Creates a scatterplot with circle size as third variable

    # Example:
    #   circlesPlot(x=rnorm(50), y=rnorm(50), z=rnorm(50))
    #   circlesPlot(x=rnorm(50), y=rnorm(50), z=rnorm(50), labels= FALSE)

    # FUNCTION:

    # Transfor Input:
    if (is.list(x)) x = matrix(unlist(x), ncol = 3)
    if (is.data.frame(x)) x = as.matrix.data.frame(x)
    if (is.matrix(x)) {
        z = x[, 3]
        y = x[, 2]
        x = x[, 1]
    }
    nX = length(x)
    nY = length(y)
    # nZ = length(z)
    stopifnot(nX == nY)
    # stopifnot(nX == nZ || nX*nY == nZ)

    # Create Circle Plot:
    if (labels) {
        plot(x, y, type = "n")
    } else {
        plot(x, y, xlab = "", ylab = "", type = "n")
    }
    symbols(x, y, add = TRUE, circles = abs(z)^scale, inches = 0.25,
        fg = "black", bg = "steelblue", ...)
    X = x[z < 0]
    Y = y[z < 0]
    Z = z[z < 0]
    symbols(X, Y, add = TRUE, circles = abs(Z)^scale, inches = 0.25,
        fg = "black", bg = "orange", ...)
    if (points) points(x, y, pch = 19)
    grid()

    # Return Value:
    invisible(NULL)
}


# ------------------------------------------------------------------------------


.perspPlot <- 
    function(x, y, z, theta = -40, phi = 30, col = "steelblue", ps = 9, ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns a perspecvtive plot

    # Notes:
    #   A synonyme call for function 'persp'

    # FUNCTION:

    # Perspective Plot:
    if (class(version) == "Sversion") {
        # we assume SPlus:
        ans = persp(x = x, y = y, z = z, ...)
    } else {
        # R:
        par(ps = ps)
        if (!exists("ticktype")) ticktype = "detailed"
        if (!exists("expand")) expand = 0.6
        if (!exists("r")) r = 500
        ans = persp(x = x, y = y, z = z, theta = theta, phi = phi,
            col = col, ticktype = ticktype, expand = expand, ...)
    }

    # Return Value:
    invisible(ans)
}


# ------------------------------------------------------------------------------


.contourPlot <- 
    function(x, y, z, ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns a contour plot

    # Notes:
    #   A synonyme call for function 'contour'

    # FUNCTION:

    # Contour Plot:
    if (class(version) == "Sversion") {
        # we assume SPlus:
        ans = contour(x = x, y = y, z = z, ...)
    } else {
        # R:
        ans = contour(x = x, y = y, z = z, ...)
    }

    # Return Value:
    invisible(ans)
}


# ------------------------------------------------------------------------------


.histStack <- 
    function(x, y = NULL, space = 0, ylab = "frequency", ...)
{   
    # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns a stacked histogram Plot

    # Example:
    #   .histStack(rnorm(1000, -1), rnorm(1000, 1))

    # FUNCTION:

    # Compute Histograms:
    breaks = hist(c(x, y))$breaks
    bars = rbind(
        hist(x, breaks = breaks, plot = FALSE)$counts,
        hist(y, breaks = breaks, plot = FALSE)$counts)

    # Plot:
    barplot(bars, space = space, ylab = ylab, ...)
    at = seq(along = breaks) - 1
    modulo = ceiling(length(at)/10)
    sel = (at%%modulo == 0)
    axis(side = 1, at = at[sel], labels = paste(breaks)[sel])

    # Return Value:
    invisible()
}


################################################################################