R:绘图函数后跟readline()

时间:2014-08-21 19:15:29

标签: r

我想在数据mpg中针对mtcars绘制不同的变量,我想逐个绘制它们,并等待下一个绘图的任何输入,所以我尝试了:

library(ggplot2)
vars = list(quote(wt), quote(cyl), quote(disp))
plot_fun <- function(var) {
  qplot(mpg, eval(var), data=mtcars)
  input <- readLines(n=1)
}
lapply(vars, plot_fun)

它没有绘制任何东西,任何人都可以告诉我正确的方法吗?

1 个答案:

答案 0 :(得分:2)

你缺少的是,当使用ggplot2时,你需要在另一个函数中调用绘图函数时执行print(qplot(...))

这是您修改的代码,以便按照您想要的方式工作。

library(ggplot2)
vars = list(quote(wt), quote(cyl), quote(disp))
plot_fun <- function(var) {
  ## this is what the `plot.lm` function uses to pause between plots; par(ask = TRUE) does the same thing
  devAskNewPage(TRUE) 

  print(qplot(mpg, eval(var), data=mtcars)) ## wrapping qplot in print makes the plot actually appear

  flush.console() ## this makes sure that the display is current
  devAskNewPage(FALSE)
}
lapply(vars, plot_fun)