简体   繁体   中英

Looping cut2 color argument in qplot

First off fair warning that this is relevant to a quiz question from coursera.org practical machine learning. However, my question does not deal with the actual question asked, but is a tangential question about plotting.

I have a training set of data and I am trying to create a plot for each predictor that includes the outcome on the y axis, the index of the data set on the x axis, and colors the plot by the predictor in order to determine the cause of bias along the index. To make the color argument more clear I am trying to use cut2() from the Hmisc package.

Here is my data:

library(ggplot2)
library(caret)
library(AppliedPredictiveModeling)
library(Hmisc)
data(concrete)
set.seed(1000)
inTrain = createDataPartition(mixtures$CompressiveStrength, p = 3/4)[[1]]
training = mixtures[ inTrain,]
testing = mixtures[-inTrain,]
training$index <- 1:nrow(training)

I tried this and it makes all the plots but they are all the same color.

plotCols <- function(x) { 
  cols <- names(x)
  for (i in 1:length(cols)) {
    assign(paste0("cutEx",i), cut2(x[ ,i]))
    print(qplot(x$index, x$CompressiveStrength, color=paste0("cutEx",i)))
  }
}
plotCols(training)

Then I tried this and it makes all the plots, and this time they are colored but the cut doesn't work.

plotCols <- function(x) { 
  cols <- names(x)
  for (i in 1:length(cols)) {
    assign(cols[i], cut2(x[ ,i]))
    print(qplot(x$index, x$CompressiveStrength, color=x[ ,cols[i]]))
  }
}
plotCols(training)

It seems qplot() doesn't like having paste() in the color argument. Does anyone know another way to loop through the color argument and still keep my cuts? Any help is greatly appreciated!

Your desired output is easier to achieve using ggplot() instead of qplot() , since you can use aes_string() , that accepts strings as arguments.

plotCols <- function(x) { 
  cols <- names(x)
  for (i in 1:length(cols)) {
    assign(paste0("cutEx", i), cut2(x[, i]))

    p <- ggplot(x) +
         aes_string("index", "CompressiveStrength", color = paste0("cutEx", i)) +
         geom_point()

    print(p)
  }
}

plotCols(training)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM