File: pairsVIM.R

package info (click to toggle)
r-cran-vim 6.2.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,556 kB
  • sloc: cpp: 141; sh: 12; makefile: 2
file content (244 lines) | stat: -rw-r--r-- 9,786 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
# --------------------------------------
# Author: Andreas Alfons, Bernd Prantner
#         Vienna University of Techology
# --------------------------------------

# workhorse for scatterplot matrices


#' Scatterplot Matrices
#' 
#' Create a scatterplot matrix.
#' 
#' This function is the workhorse for [marginmatrix()] and
#' [scattmatrixMiss()].
#' 
#' The graphical parameter `oma` will be set unless supplied as an
#' argument.
#' 
#' A panel function should not attempt to start a new plot, since the
#' coordinate system for each panel is set up by `pairsVIM`.
#' 
#' @param x a matrix or `data.frame`.
#' @param delimiter a character-vector to distinguish between variables and
#' imputation-indices for imputed variables (therefore, `x` needs to have
#' [colnames()]). If given, it is used to determine the corresponding
#' imputation-index for any imputed variable (a logical-vector indicating which
#' values of the variable have been imputed). If such imputation-indices are
#' found, they are used for highlighting and the colors are adjusted according
#' to the given colors for imputed variables (see `col`).
#' @param main,sub main and sub title.
#' @param panel a \code{function(x, y, \dots{})}, which is used to plot the
#' contents of each off-diagonal panel of the display.
#' @param \dots further arguments and graphical parameters to be passed down.
#' `par("oma")` will be set appropriately unless supplied (see
#' [graphics::par()]).
#' @param lower,upper separate panel functions to be used below and above the
#' diagonal, respectively.
#' @param diagonal optional \code{function(x, \dots{})} to be applied on the
#' diagonal panels.
#' @param labels either a logical indicating whether labels should be plotted
#' in the diagonal panels, or a character vector giving the labels.
#' @param pos.labels the vertical position of the labels in the diagonal
#' panels.
#' @param cex.labels the character expansion factor to be used for the labels.
#' @param font.labels the font to be used for the labels.
#' @param layout a character string giving the layout of the scatterplot
#' matrix.  Possible values are `"matrix"` (a matrix-like layout with the
#' first row on top) and `"graph"` (a graph-like layout with the first row
#' at the bottom).
#' @param gap a numeric value giving the distance between the panels in margin
#' lines.
#' @note The code is based on [graphics::pairs()].  Starting with
#' version 1.4, infinite values are no longer removed before passing the
#' `x` and `y` vectors to the panel functions.
#' @author Andreas Alfons, modifications by Bernd Prantner
#' @seealso [marginmatrix()], [scattmatrixMiss()]
#' @references M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete
#' data using visualization tools.  *Journal of Advances in Data Analysis
#' and Classification*, Online first. DOI: 10.1007/s11634-011-0102-y.
#' @keywords hplot
#' @family plotting functions
#' @examples
#' 
#' data(sleep, package = "VIM")
#' x <- sleep[, -(8:10)]
#' x[,c(1,2,4,6,7)] <- log10(x[,c(1,2,4,6,7)])
#' pairsVIM(x)
#' 
#' @export pairsVIM
pairsVIM <- function(x, ..., delimiter = NULL, main = NULL, sub = NULL, panel = points, 
        lower = panel, upper = panel, diagonal = NULL, 
        labels = TRUE, pos.labels = NULL, cex.labels = NULL, 
        font.labels = par("font"), layout = c("matrix","graph"), 
        gap = 1) {
    
    # additional arguments
    dots <- list(...)
    nmdots <- names(dots)
    
    # initializations and error messages
    if(!(inherits(x, c("data.frame","matrix")))) {
        stop("'x' must be a data.frame or matrix")
    }
	imputed <- FALSE # indicates if there are Variables with missing-index
	## delimiter ##
	if(!is.null(delimiter)) {
		tmp <- grep(delimiter, colnames(x)) # Position of the missing-index
		if(length(tmp) > 0) {
			imp_var <- x[, tmp, drop=FALSE]
			x <- x[, -tmp, drop=FALSE]
			
			if(ncol(x) == 0) stop("Only the missing-index is given")
			if(is.matrix(imp_var) && range(imp_var) == c(0,1)) imp_var <- apply(imp_var,2,as.logical)
			
			if(is.null(dim(imp_var))) {
				if(!is.logical(imp_var)) stop("The missing-index of imputed Variables must be of the type logical")
			} else {
				if(!any(as.logical(lapply(imp_var,is.logical)))) stop("The missing-index of imputed Variables must be of the type logical")	
			}
			imputed <- TRUE
		} else {
			warning("'delimiter' is given, but no missing-index-Variable is found", call. = FALSE)
		}
	}
    n <- nrow(x)
    p <- ncol(x)
    if(p < 2) stop("'x' must be at least 2-dimensional")
    # prepare data
    if(is.data.frame(x)) x <- data.matrix(x)
    else if(mode(x) != "numeric") mode(x) <- "numeric"
    if(is.null(colnames(x))) colnames(x) <- defaultNames(p)
    
    # panel functions
    has.lower <- !is.null(lower)
    has.upper <- !is.null(upper)
    has.diag  <- !is.null(diagonal)
    panel <- match.fun(panel)
    if(has.lower && !missing(lower)) lower <- match.fun(lower)
    if(has.upper && !missing(upper)) upper <- match.fun(upper)
    if(has.diag && !missing(diagonal)) diagonal <- match.fun(diagonal)
    
    # use matrix or graph-like layout?
    layout <- match.arg(layout)
    row1attop <- layout == "matrix"
    if(!row1attop) {
        tmp <- has.lower
        has.lower <- has.upper
        has.upper <- tmp
        tmp <- lower
        lower <- upper
        upper <- tmp
    }
    
    # default labels for diagonal panels
    has.labs <- TRUE
    if(is.null(labels)) labels <- colnames(x)
    else if(is.logical(labels)) {
        if(!is.na(labels) && labels) labels <- colnames(x)
        else has.labs <- FALSE
    } else labels <- rep(labels, length.out=p)
    rf <- if(p == 2) 5/6 else 2/3
    if(is.null(cex.labels)) cex.labels <- 1/rf
    if(is.null(pos.labels)) pos.labels <- 0.5 + has.diag/3
    
    # local functions
    initializePlot <- function(..., main, sub, col, bg, pch, cex, lty, lwd) {
        plot.new()
        plot.window(...)
    }
    localLower <- function(..., log, main, sub) lower(...)
    localUpper <- function(..., log, main, sub) upper(...)
    localDiagonal <- function(..., log, main, sub) diagonal(...)
    localAxis <- function(..., log, col, bg, pch, cex, lty, lwd, xpd) {
        axis(..., xpd=NA)
    }
    localBox <- function(..., log, col, bg, pch, cex, lty, lwd) box(...)
    localTitle <- function(..., log, xlab, ylab, outer, 
        cex.main = par("cex.main"), cex.sub = par("cex.sub"), 
        col, bg, pch, cex, lty, lwd) {
        title(..., cex.main=cex.main/rf, cex.sub=cex.sub/rf, outer=TRUE)
    }
    localText <- function(..., log, col, bg, pch, cex, lty, lwd, font) {
        text(..., cex=cex.labels, font=font.labels)
    }
    localStrwidth <- function(..., log, col, bg, pch, cex, lty, lwd, font) {
        strwidth(..., cex=cex.labels, font=font.labels)
    }
    localStrheight <- function(..., log, col, bg, pch, cex, lty, lwd, font) {
        strheight(..., cex=cex.labels, font=font.labels)
    }
    
    # set outer margin
    oma <- if("oma" %in% nmdots) dots$oma else NULL
    if(is.null(oma)) {
        oma <- rep.int(4, 4)
        if(!is.null(main)) oma[3] <- 6
        if(!is.null(sub)) oma[1] <- 5
    }
    op <- par(mfrow=c(p, p), mar = rep.int(gap/2, 4), oma = oma)
    op$usr <- c(0,1,0,1)
    on.exit(par(op))
    
    # check for infinite values
    iInf <- is.infinite(x)
    for(i in 1:p) {
        if(any(iInf[, i])) {
            warning(gettextf("variable '%s' contains infinite values", 
                    colnames(x)[i]))
        }
    }
    # create plot
    for(i in if(row1attop) 1:p else p:1) {
        for(j in 1:p) {
#            ind <- !iInf[, j] & !iInf[, i]
#            xj <- x[ind, j]
#            xi <- x[ind, i]
#            rxj <- if(all(is.na(xj))) c(0,0) else range(xj, na.rm=TRUE)
#            rxi <- if(all(is.na(xi))) c(0,0) else range(xi, na.rm=TRUE)
            xj <- x[, j, drop = FALSE]
            xi <- x[, i, drop = FALSE]
            rxj <- if(any(is.finite(xj))) range(xj, finite=TRUE) else c(0,0)
            rxi <- if(any(is.finite(xi))) range(xi, finite=TRUE) else c(0,0)
            initializePlot(rxj, rxi, ...)
            if(i == j || (i < j && has.lower) || (i > j && has.upper)) {
                mfg <- par("mfg")
				if(imputed) xj <- cbind(xj, imp_var)
                if(i == j) {
                    if(has.diag) localDiagonal(xi, ...)
                    if(has.labs) {
                        par(xlog=FALSE, ylog=FALSE, usr=c(0,1,0,1))
                        if(is.null(cex.labels)) {
                        }
                        lab.width <- localStrwidth(labels[i], ...)
                        lab.height <- localStrheight(labels[i], ...)
                        if(lab.width < 1 && lab.height < 1) {
                            localText(0.5, pos.labels, labels[i], ...)
                        }
                    }
                } else if(i < j) localLower(xj, xi, ...)
                else localUpper(xj, xi, ...)
                if(any(par("mfg") != mfg)) {
                    stop("the panel function made a new plot")
                }
                if(i == 1  && (!(j %% 2) || !has.upper || !has.lower)) {
                    localAxis(1 + 2*row1attop, ...)
                }
                if(i == p && (j %% 2  || !has.upper || !has.lower)) {
                    localAxis(3 - 2*row1attop, ...)
                }
                if(j == 1  && (!(i %% 2) || !has.upper || !has.lower)) {
                    localAxis(2, ...)
                }
                if(j == p && (i %% 2 || !has.upper || !has.lower)) {
                    localAxis(4, ...)
                }
                localBox(...)
            } else par(new=FALSE)
        }
    }
    
    # main and sub title
    localTitle(main=main, sub=sub, ...)
    invisible()
}