File: ggscatmat.R

package info (click to toggle)
r-cran-ggally 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,136 kB
  • sloc: sh: 13; makefile: 2
file content (324 lines) | stat: -rw-r--r-- 11,233 bytes parent folder | download
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
if (getRversion() >= "2.15.1") {
  utils::globalVariables(c("xvalue", "yvalue"))
}


#' lowertriangle - rearrange dataset as the preparation of ggscatmat function
#'
#' function for making the melted dataset used to plot the lowertriangle scatterplots.
#'
#' @export
#' @param data a data matrix. Should contain numerical (continuous) data.
#' @param columns an option to choose the column to be used in the raw dataset. Defaults to \code{1:ncol(data)}
#' @param color an option to choose a factor variable to be grouped with. Defaults to \code{(NULL)}
#' @author Mengjia Ni, Di Cook \email{dicook@@monash.edu}
#' @examples
#' data(flea)
#' head(lowertriangle(flea, columns= 2:4))
#' head(lowertriangle(flea))
#' head(lowertriangle(flea, color="species"))
lowertriangle <- function(data, columns=1:ncol(data), color=NULL) {
  data <- upgrade_scatmat_data(data)
  data.choose <- data[columns]
  dn <- data.choose[sapply(data.choose, is.numeric)]
  factor <- data[sapply(data, is.factor)]
  p <- ncol(dn)
  newdata <- NULL
  for (i in 1:p) {
    for (j in 1:p) {
      newdata <- rbind(newdata,
                       cbind(dn[[i]], dn[[j]], i, j, colnames(dn)[i], colnames(dn)[j], factor)
      )
    }
  }
  colnames(newdata) <- c("xvalue", "yvalue", "xslot", "yslot", "xlab", "ylab", colnames(factor))

  rp <- data.frame(newdata)
  rp[[2]][rp[[3]] >= rp[[4]]] <- "NA"
  rp[[1]][rp[[3]] > rp[[4]]] <- "NA"

  rp$xvalue <- suppressWarnings(as.numeric(as.character(rp$xvalue)))
  rp$yvalue <- suppressWarnings(as.numeric(as.character(rp$yvalue)))

  if (is.null(color)){
    rp.new <- rp[1:6]
  } else {
    colorcolumn <- rp[[which(colnames(rp) == color)]]
    rp.new <- cbind(rp[1:6], colorcolumn)
  }
  return(rp.new)
}

#' uppertriangle - rearrange dataset as the preparation of ggscatmat function
#'
#' function for making the dataset used to plot the uppertriangle plots.
#'
#' @export
#' @param data a data matrix. Should contain numerical (continuous) data.
#' @param columns an option to choose the column to be used in the raw dataset. Defaults to \code{1:ncol(data)}
#' @param color an option to choose a factor variable to be grouped with. Defaults to \code{(NULL)}
#' @param corMethod method argument supplied to \code{\link[stats]{cor}}
#' @author Mengjia Ni, Di Cook \email{dicook@@monash.edu}
#' @importFrom stats cor
#' @examples
#' data(flea)
#' head(uppertriangle(flea, columns=2:4))
#' head(uppertriangle(flea))
#' head(uppertriangle(flea, color="species"))
uppertriangle <- function(data, columns=1:ncol(data), color=NULL, corMethod = "pearson") {
  data <- upgrade_scatmat_data(data)
  data.choose <- data[columns]
  dn <- data.choose[sapply(data.choose, is.numeric)]
  factor <- data[sapply(data, is.factor)]
  p <- ncol(dn)
  newdata <- NULL
  for (i in 1:p) {
    for (j in 1:p) {
      newdata <- rbind(newdata,
                       cbind(dn[, i], dn[, j], i, j, colnames(dn)[i], colnames(dn)[j],
                             min(dn[, i]) + 0.5 * (max(dn[, i]) - min(dn[, i])),
                             min(dn[, j]) + 0.5 * (max(dn[, j]) - min(dn[, j])), factor)
      )
    }
  }
  colnames(newdata) <- c(
    "xvalue", "yvalue",
    "xslot", "yslot",
    "xlab", "ylab",
    "xcenter", "ycenter",
    colnames(factor)
  )

  rp <- data.frame(newdata)
  rp[[2]][rp[[3]] <= rp[[4]]] <- "NA"
  rp[[1]][rp[[3]] < rp[[4]]] <- "NA"

  rp$xvalue <- suppressWarnings(as.numeric(as.character(rp$xvalue)))
  rp$yvalue <- suppressWarnings(as.numeric(as.character(rp$yvalue)))

  if (is.null(color)){
    rp.new <- rp[1:8]
  }else{
    colorcolumn <- rp[[which(colnames(rp) == color)]]
    rp.new <- cbind(rp[1:8],  colorcolumn)
  }
  a <- rp.new
  b <- subset(a, (a$yvalue != "NA") & (a$xvalue != "NA"))
  if (is.null(color)){
    data.cor <- ddply(
      b, .(ylab, xlab),
      function(subsetDt) {
        xlab <- subsetDt$xlab
        ylab <- subsetDt$ylab
        xvalue <- subsetDt$xvalue
        yvalue <- subsetDt$yvalue

        if (identical(corMethod, "rsquare")) {
          r <- cor(
            xvalue, yvalue,
            use = "pairwise.complete.obs",
            method = "pearson"
          )
          r <- r ^ 2
        } else {
          r <- cor(
            xvalue, yvalue,
            use = "pairwise.complete.obs",
            method = corMethod
          )
        }
        r <- paste(round(r, digits = 2))

        data.frame(
          xlab = unique(xlab), ylab = unique(ylab),
          r = r,
          xvalue = min(xvalue) + 0.5 * (max(xvalue) - min(xvalue)),
          yvalue = min(yvalue) + 0.5 * (max(yvalue) - min(yvalue))
        )
      }
    )
    return(data.cor)

  }else{
    c <- b
    data.cor1 <- ddply(
      c, .(ylab, xlab, colorcolumn),
      function(subsetDt) {
        xlab <- subsetDt$xlab
        ylab <- subsetDt$ylab
        colorcolumn <- subsetDt$colorcolumn
        xvalue <- subsetDt$xvalue
        yvalue <- subsetDt$yvalue

        if (identical(corMethod, "rsquare")) {
          r <- cor(
            xvalue, yvalue,
            use = "pairwise.complete.obs",
            method = "pearson"
          )
          r <- r ^ 2
        } else {
          r <- cor(
            xvalue, yvalue,
            use = "pairwise.complete.obs",
            method = corMethod
          )
        }
        r <- paste(round(r, digits = 2))
        data.frame(
          ylab = unique(ylab), xlab = unique(xlab), colorcolumn = unique(colorcolumn),
          r = r
        )
      }
    )

    n <- nrow(data.frame(unique(b$colorcolumn)))
    position <- ddply(b, .(ylab, xlab), summarise,
                      xvalue = min(xvalue) + 0.5 * (max(xvalue) - min(xvalue)),
                      ymin = min(yvalue),
                      ymax = max(yvalue),
                      range = max(yvalue) - min(yvalue))
    df <- data.frame()
    for (i in 1:nrow(position)) {
      for (j in 1:n){
        row <- position[i, ]
        df <- rbind(df, cbind(row[, 3], (row[, 4] + row[, 6] * j / (n + 1))))
      }
    }
    data.cor <- cbind(data.cor1, df)
    colnames(data.cor) <- c("ylab", "xlab", "colorcolumn", "r", "xvalue", "yvalue")
    return(data.cor)
  }
}

#' scatmat - plot the lowertriangle plots and density plots of the scatter plot matrix.
#'
#' function for making scatterplots in the lower triangle and diagonal density plots.
#'
#' @export
#' @param data a data matrix. Should contain numerical (continuous) data.
#' @param columns an option to choose the column to be used in the raw dataset. Defaults to \code{1:ncol(data)}
#' @param color an option to group the dataset by the factor variable and color them by different colors. Defaults to \code{NULL}
#' @param alpha an option to set the transparency in scatterplots for large data. Defaults to \code{1}.
#' @author Mengjia Ni, Di Cook \email{dicook@@monash.edu}
#' @examples
#' data(flea)
#' scatmat(flea, columns=2:4)
#' scatmat(flea, columns= 2:4, color="species")
scatmat <- function(data, columns=1:ncol(data), color=NULL, alpha=1) {
  data <- upgrade_scatmat_data(data)
  data.choose <- data[columns]
  dn <- data.choose[sapply(data.choose, is.numeric)]
  if (ncol(dn) == 0) {
    stop("All of your variables are factors. Need numeric variables to make scatterplot matrix.")
  } else {
    ltdata.new <- lowertriangle(data, columns = columns, color = color)
    r <- ggplot(ltdata.new, mapping = aes_string(x = "xvalue", y = "yvalue")) +
      theme(axis.title.x = element_blank(), axis.title.y = element_blank()) +
      facet_grid(ylab ~ xlab, scales = "free") +
      theme(aspect.ratio = 1)
    if (is.null(color)) {
      densities <- do.call("rbind", lapply(1:ncol(dn), function(i) {
        data.frame(xlab = names(dn)[i], ylab = names(dn)[i],
                   x = dn[, i])
      }))
      for (m in 1:ncol(dn)) {
        j <- subset(densities, xlab == names(dn)[m])
        r <- r + stat_density(
          aes(
            x = x,
            y = ..scaled.. * diff(range(x)) + min(x) # nolint
          ),
          data = j, position = "identity", geom = "line", color = "black")
      }
      r <- r + geom_point(alpha = alpha, na.rm = TRUE)
      return(r)
    } else {
      densities <- do.call("rbind", lapply(1:ncol(dn), function(i) {
        data.frame(xlab = names(dn)[i], ylab = names(dn)[i],
                   x = dn[, i], colorcolumn = data[, which(colnames(data) == color)])
      }))
      for (m in 1:ncol(dn)) {
        j <- subset(densities, xlab == names(dn)[m])
        r <- r +
          stat_density(
            aes_string(
              x = "x", y = "..scaled.. * diff(range(x)) + min(x)",
              colour = "colorcolumn"
            ),
            data = j,
            position = "identity",
            geom = "line"
          )
      }
      r <- r +
        geom_point(
          data = ltdata.new,
          aes_string(colour = "colorcolumn"),
          alpha = alpha,
          na.rm = TRUE
        )
      return(r)
    }
  }
}

#' ggscatmat - a traditional scatterplot matrix for purely quantitative variables
#'
#' This function makes a scatterplot matrix for quantitative variables with density plots on the diagonal
#' and correlation printed in the upper triangle.
#'
#' @export
#' @param data a data matrix. Should contain numerical (continuous) data.
#' @param columns an option to choose the column to be used in the raw dataset. Defaults to \code{1:ncol(data)}.
#' @param color an option to group the dataset by the factor variable and color them by different colors. Defaults to \code{NULL}.
#' @param alpha an option to set the transparency in scatterplots for large data. Defaults to \code{1}.
#' @param corMethod method argument supplied to \code{\link[stats]{cor}}
#' @author Mengjia Ni, Di Cook \email{dicook@@monash.edu}
#' @examples
#' data(flea)
#' ggscatmat(flea, columns = 2:4)
#' ggscatmat(flea, columns = 2:4, color = "species")
ggscatmat <- function(data, columns = 1:ncol(data), color = NULL, alpha = 1, corMethod = "pearson"){

  data <- upgrade_scatmat_data(data)
  data.choose <- data[columns]
  dn <- data.choose[sapply(data.choose, is.numeric)]

  if (ncol(dn) == 0) {
    stop("All of your variables are factors. Need numeric variables to make scatterplot matrix.")
  }
  if (ncol(dn) < 2){
    stop ("Not enough numeric variables to make a scatter plot matrix")
  }

  a <- uppertriangle(data, columns = columns, color = color, corMethod = corMethod)
  if (is.null(color)){
    plot <- scatmat(data, columns = columns, alpha = alpha) +
      geom_text(data = a, aes_string(label = "r"), colour = "black")
  } else {
    plot <- scatmat(data, columns = columns, color = color, alpha = alpha) +
      geom_text(data = a, aes_string(label = "r", color = "colorcolumn")) + labs(color = color)
  }
  factor <- data.choose[sapply(data.choose, is.factor)]
  if (ncol(factor) == 0){
    return(plot)
  } else {
    warning("Factor variables are omitted in plot")
    return(plot)
  }
}


upgrade_scatmat_data <- function(data) {
  data <- as.data.frame(data)
  dataIsCharacter <- sapply(data, is.character)
  if (any(dataIsCharacter)) {
    dataCharacterColumns <- names(dataIsCharacter[dataIsCharacter])
    for (dataCol in dataCharacterColumns) {
      data[[dataCol]] <- as.factor(data[[dataCol]])
    }
  }

  data
}