【问题标题】:Use of ggplot() within a for-loop in another function in R without returning a graph object?在R中另一个函数的for循环中使用ggplot()而不返回图形对象?
【发布时间】:2014-11-01 19:06:34
【问题描述】:

所有,我的任务是编写一个返回列表作为输出的函数。 同时,绘制一些东西。

使用mtcars数据说我的功能如下

library(ggplot2)    
data(mtcars)
myfunc<-function(mtcars){
  for(i in 1:ncol(mtcars)){
    g1<- ggplot(mtcars, aes(x=mtcars[,i]))
    g1 + geom_histogram()+
    geom_vline(xintercept=mean(mtcars[,i]),col="red")
  }
  return (list(mtcars))
}

myfunc(mtcars)

我怎样才能修改上面的代码,返回一个想要的列表并显示gglots?

【问题讨论】:

  • data.frames 列表,在我的示例中,我只是将原始数据作为列表返回。这只是一个例子
  • @jlhoward 如果您能解决,将不胜感激,谢谢。

标签: r function ggplot2 dataframe histogram


【解决方案1】:

如果您的问题是“为什么不显示任何图?”,那么答案是这样的:

在 R 命令行中,只需键入变量名或表达式即可调用 print 方法。这不会发生在函数、循环或使用source(...) 时,因此要显示任何内容(打印或绘图),您需要明确执行此操作。但这只是你的问题的一部分。

aes(...) 调用中使用索引是一个非常糟糕的主意。相反,提取列名并在调用 aes_string(...) 时使用它:

myfunc<-function(mtcars){
  for(i in 1:ncol(mtcars)){
    col <- names(mtcars)[i]
    ggp <- ggplot(mtcars, aes_string(x=col))+
      geom_histogram()+
      geom_vline(xintercept=mean(mtcars[[col]]),col="red")
    plot(ggp)
  }
  return (list(mtcars))
}

myfunc(mtcars)

这将绘制直方图。

【讨论】:

  • 谢谢,@jlhoward,我可以在此函数中将 bin 大小指定为向量吗?
猜你喜欢
  • 1970-01-01
  • 2017-08-26
  • 2021-01-06
  • 2022-08-24
  • 2016-05-05
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多