1

I want to plot different variables against mpg in data mtcars, I want to plot them one by one, and wait for my any input for next plot, so I tried:

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)

it doesn't plot anything, anybody can show me the correct way?

user3684014
  • 1,175
  • 12
  • 26
  • http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f – Dason Aug 21 '14 at 20:40

1 Answers1

3

What you are missing is that with ggplot2 you need to do print(qplot(...)) when the plotting function is called from within another function.

Here's your code modified to work in the way that you want.

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)
jld
  • 466
  • 10
  • 20