ggplot's qplot does not execute on sourcing

RGgplot2R Faq

R Problem Overview


Let's assume I have 2 source files, the first one named example1.r and the second one example2.r (given below).

example1.r

plot(1:10,1:10)

example2.r

qplot(1:10,1:10)

When I source example1.r, the graph is drawn. It does not, however, when I source example2.r. What is the solution here?

(qplot in example2.r is ggplot2's function)

R Solutions


Solution 1 - R

Update:

  • .R files: source's option print.eval=TRUE will lead to printing behaviour of the evaluation result like in the interactive command line.

>source("Script.R", print.eval=TRUE)

  • .Rnw files: knitr by default emulates the behaviour of the interactive command line wrt. printing. Note that knitr can be specified as Sweaving engine also for R package vignettes.


This is my original answer. But note that this workaround is IMHO completely obsolete now (and it always was good for a small lazy niche only).

This is the famous FAQ 7.22: Why do lattice/trellis graphics not work?.

For grid graphics like ggplot2 or lattice, you need to print the graphics object in order to actually draw it.

Interactively on the command line this is done automatically. Everywhere else (inside files to be sourced, loops, functions, Sweave chunks) you need to print it explicitly.

print (qplot (1 : 10, 1 : 10))

Alternatively, you can redefine qplot to do the printing:

qplot <- function (x, y = NULL, z = NULL, ...) {
  p <- ggplot2::qplot (x = x, y = y, z = z, ...)
  print (p)
}

(this changes the axis labels to x and y).

I use this approach in vignettes where I want to write code exactly as a user in an interactive session would type it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGrega KešpretView Question on Stackoverflow
Solution 1 - Rcbeleites unhappy with SXView Answer on Stackoverflow