【问题标题】:Looping cut2 color argument in qplot在 qplot 中循环 cut2 颜色参数
【发布时间】:2018-02-09 16:02:02
【问题描述】:

首先公平地警告说,这与 coursera.org 实用机器学习中的一个测验问题有关。但是,我的问题并不涉及所提出的实际问题,而是关于绘图的切线问题。

我有一个训练数据集,我正在尝试为每个预测变量创建一个图,其中包括 y 轴上的结果、x 轴上数据集的索引,并按顺序为预测变量着色确定沿指数偏差的原因。为了使颜色参数更清晰,我尝试使用 Hmisc 包中的cut2()

这是我的数据:

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)

我试过这个,它可以绘制所有的图,但它们都是相同的颜色。

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)

然后我尝试了这个,它制作了所有的情节,这次它们是彩色的,但剪切不起作用。

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)

似乎qplot() 不喜欢在颜色参数中包含paste()。有谁知道另一种循环颜色参数并仍然保留我的剪辑的方法?非常感谢任何帮助!

【问题讨论】:

    标签: r loops ggplot2 hmisc


    【解决方案1】:

    使用ggplot() 而不是qplot() 更容易实现您想要的输出,因为您可以使用接受字符串作为参数的aes_string()

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-29
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      相关资源
      最近更新 更多