ggplot没有显示

时间:2018-02-12 00:29:31

标签: r ggplot2

我编写了一个函数,用于绘制(在Base R和ggplot中)KNN分类问题中各种K值的错误分类率。我的问题是,当Base R图显示时,ggplot图不显示。当我从函数中取出ggplot代码时,它可以工作。我不确定我做错了什么。

有人可以指出我做错了吗?

代码:

library(ISLR)
library(ggplot2)
library(class)

data("Weekly")
train <- (Weekly$Year < 2009)
Weekly.train <- Weekly[ train, ]
Weekly.test <- Weekly[ !train, ]

knn.train.x <- scale( as.data.frame(Weekly$Lag2[train]) )
knn.test.x <- scale( as.data.frame(Weekly$Lag2[!train]) )
train.Direction <- Weekly$Direction[train]
set.seed(1234)

#Function for choosing k in knn
misclassknn <- function(train, test, 
                    response.train, 
                    response.test, 
                    Kmax){ 
  K <- 1:Kmax
  misclass <- numeric(Kmax)
  for( k in K){
    knn.pred <- knn(train,test,response.train, k=k)
    misclass[k] <- mean(knn.pred!=response.test)
  }
  # base R
  plot(c(1, Kmax), c(0, 1), type = "n", 
       main = "Misclassification Rate for K Values",
       xlab = "K", ylab = "Misclassification Rate")
  points(1 : Kmax, misclass, type = "b", pch = 16)

  # ggplot
  df <- data.frame(1 : Kmax, misclass)
  names(df) <- c("misclass", "K")
   ggplot(df, aes(x = misclass, y = K)) + geom_line() + ylim(0, 1) +
    geom_point() + labs( title = "Misclassification Rate for K Values", 
                     y = "Misclassification Rate", x = "K")

  return(list(K = Kmax, misclass = misclass, 
          Kmin = which.min(misclass)))
}

misclassknn(train = knn.train.x, 
        test = knn.test.x, 
        response.train = train.Direction,
        response.test = Weekly$Direction[!train], 
        Kmax = 15)

1 个答案:

答案 0 :(得分:3)

我们理所当然地认为绘制R的工作方式。对于ggplot,它实际上返回一个对象,这是一个如何构建绘图的描述。在函数内部,由于范围不同,事物不会像在全局范围内那样显示。基本上你需要手动告诉它通过在ggplot命令周围包装function addverse() { connection.query('SELECT versetext, book, mp3, id, reference FROM myverses where mp3 = "empty" limit 1', function (error, results, fields) { console.log(error); var scripture = results[0].versetext; var book = results[0].book; var reference = results[0].reference.replace(":", " verse "); console.log(scripture + " " + book.replace("1", "first").replace("2", "second").replace("3", "third") + " " + reference); var myverse = scripture + " " + book.replace("1", "first").replace("2", "second").replace("3", "third") + " " + reference; var link = "https://s3.amazonaws.com/myverses/" + book.replace(/ /g, "")+reference.replace(/ /g, "")+".mp3" function linkit(){ connection.query('update myverses set mp3 = ? where mp3 = "empty" limit 1', [link], function (error, results, fields) { console.log(error) }) } txtomp3.getMp3(myverse, function(err, binaryStream){ if(err){ console.log(err); return; } function writeit() { var file = fs.createWriteStream("myverse.mp3"); console.log('recording the verse') file.write(binaryStream); file.end(); } function uploadit () { console.log('uploading the verse') AWS.config.update({ accessKeyId: '...', secretAccessKey: '...' }); var s3 = new AWS.S3(); s3.putObject({ Bucket: 'myverses', Key: book.replace(/ /g, "")+reference.replace(/ /g, "")+".mp3", Body: myvalue, ACL: 'public-read' },function (resp) { console.log(arguments); console.log('Successfully uploaded the verse.'); addanother(); });} writeit(); var myvalue = fs.createReadStream("myverse.mp3"); setTimeout(uploadit, 3000) }); }); } print()来显示绘图,或者你需要将对象作为函数的输出返回,然后从全局调用它范围。基本上你只是强迫它显示对象。

将ggplot对象存储为类似

的常见内容
ggplot_build

现在,对象p <- ggplot(etc) + geom_etc() + ... 可以根据需要构建到图表中。您可以使用p(或print(p)),也可以在主代码中使用ggplot_build(p),如果函数返回的话,例如p