0

I have a bunch of different graphs that I am trying to make, and I want to have an individual R file for each graph in addition to an R file that sources all of these R files.

This makes it easier to find and edit things since there is only code for one graph in each R file, but I still want to be able to make all of the graphs at once.

I thought I would be able to do this by having an R that just sources all of the individual R files that make the graphs.

However, executing the the test2.R script leads to a blank PDF file being created in ~/Documents/, whereas uncommenting the first two lines of test.R and just running that R script by itself leads to the expected PDF file in ~/Documents/.

Why is this the case? Is there a way to fix it?

test.R (saved as ~/Desktop/test.R)

#library(ggplot2)
#library(Cairo)
CarPlot <- ggplot() +
    stat_summary(data = mtcars,
                 aes(x = factor(gear),
                     y = mpg,
                     fill = factor(gear)
                     ),
                 fun.y = "mean",
                 geom = "bar"
                 )
setwd("~/Documents/")
CairoPDF(file = "CarPlot.pdf")
CarPlot
dev.off()

test2.R (saved as ~/Desktop/test2.R)

library(ggplot2)
library(Cairo)
source(file = "~/Desktop/test.R")
Adam Liter
  • 875
  • 2
  • 10
  • 30
  • Be sure to actually print the plot: `print(CarPlot)`. Plots aren't automatically drawn when running non-interactively via `source()`. – MrFlick Jun 03 '15 at 18:03
  • @MrFlick Hmm, adding `print(CarPlot)` to `test.R` does *not* fix the problem. However, setting `print.eval = TRUE` inside the call to `source()` does fix the problem. – Adam Liter Jun 03 '15 at 18:06
  • That seems highly unlikely, but at least you got something that works. You did replace the `CarPlot` with `print(CarPlot`) in between the `CairoPDF()` and `dev.off()`? – MrFlick Jun 03 '15 at 18:10
  • @MrFlick Ah, oops. Forgot to save the change before executing the script. It does indeed work with `print()` as well. Thanks for the quick response! You can go ahead and vote to close this as a duplicate if you'd like. I appreciate it! – Adam Liter Jun 03 '15 at 18:12

0 Answers0