Cannot create PDF by ggplot2 within if-statements - r

Consider a minimal example: generating an empty plot with ggplot2 and put it into a PDF file. Typically people would do
pdf()
ggplot()
dev.off()
and it works as expected. However, when you wrap these statements into an if-statement, the resulting PDF file becomes corrupted.
if (TRUE) {
pdf()
ggplot()
dev.off()
}
This issue has been reproduced on both Windows 10 and macOS Mojave. I'm using the latest version of R
$ R --version
R version 3.6.0 (2019-04-26) -- "Planting of a Tree"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin18.6.0 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
https://www.gnu.org/licenses/.

To save a ggplot object using pdf or jpg functions, one has to explicitly print the ggplot.
if (TRUE) {
pdf()
print(ggplot())
dev.off()
}
This is stated in R-FAQ 7.22 Why do lattice/trellis graphics not work?
The most likely reason is that you forgot to tell R to display the graph. Lattice functions
such as xyplot() create a graph object, but do not display it (the
same is true of ggplot2 graphics, and Trellis graphics in S-PLUS). The
print() method for the graph object produces the actual display. When
you use these functions interactively at the command line, the result
is automatically printed, but in source() or inside your own functions
you will need an explicit print() statement.
So, it would not save if one simply source a script even in the absence of a conditional statement or loop (source with echo = TRUE would save the plot).
I personally prefer to use the ggsave function since it seems more flexible.
if (TRUE) {
ggplot()
ggave(filename = "plot.pdf")
}

Related

R: Change default jpeg() export quality via console

how can I change the default jpeg() export quality via console in R version 4.0.3 (2020-10-10) -- "Bunny-Wunnies Freak Out"?
Here is an example: jpeg('../data/all/graphic1.jpg', quality=100)
But I don't want to change all separate jpeg() command...
Thanks for your help
You could define a new function that over-rides the default function with a version such as:
jpeg <- function(filename, quality=100, ...) grDevices::jpeg(filename, quality, ...)
This would work for most common situations where the jpeg function is used (say in a user script), but may not work correctly when the jpeg function is being called from within functions in other packages.

Unable to save/open pdf file in R

I am new to R programming and I am trying to learn it. So, please bear with me if this question is silly!
I am trying to execute the below code in RStudio and I get the following error:
R version 3.6.2 (2019-12-12) -- "Dark and Stormy Night"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)
[Workspace loaded from ~/.RData]
> x=rnorm(100)
> y=rnorm(100)
> pdf("Figure.pdf")
**Error in pdf("Figure.pdf") : cannot open file 'Figure.pdf'**
> plot(x,y, col="green")
> dev.off()
null device
I am unable to save or open the pdf file. I tried t o check my permissions and I also ran the Rstudio with administer rights but no luck!
One can direct the output of R graphics functions to PDF files through the use of the pdf() function.
The file = argument is a named argument (versus a positional argument), and therefore one needs to use the name in order to change its value. The reasoning for this is that the PDF device function's default value for file = allows multiple PDFs to be written, per the R documentation for pdf().
x=rnorm(100)
y=rnorm(100)
pdf(file = "Figure.pdf")
plot(x,y, col="green")
dev.off()
...produces a PDF in the current R working directory that contains the following image.

An issue with tiff and ggplot R functions inside for loop

]
2
I was not able to get a batch of images with tiff() R function inside for loop.
I have x86_64-w64-mingw32/x64 (64-bit) platform with installed Windows 8.1 and RStudio Version 1.0.143 with R version 3.6.0 (2019-04-26) -- "Planting of a Tree". I tried to obtaine a batch of tiff images by putting my code inside the for loop. Unfortunately that resulted in the numerous broken files (in attachment). But if i type exactly the same code in the RStudio console i got normal (valid) image.
#Fragment of the script
for (i in 1:nrow(BH))
{
...
tiff( paste(pos$rs[1],"tiff",sep = '.'))
ggplot(df_g_,aes(x=factor(g),fill=factor(O)))+geom_bar(stat="count")+xlab("")+labs(fill='')
dev.off()
}
#If i perform the following code in console after script execution i got a valid image
tiff( paste(pos$rs[1],"tiff",sep = '.'))
ggplot(df_g_,aes(x=factor(g),fill=factor(O)))+geom_bar(stat="count")+xlab("")+labs(fill='')
dev.off()
The solution was to envelop ggplotfunction by base print function in the loop:
print(ggplot(df_g_,aes(x=factor(g),fill=factor(O)))+geom_bar(stat="count")+xlab("")+labs(fill=''))
So, i've used the solution from the other post:
enter link description here

rgl.postscript: file saved without varying text sizes

From #DWin and #Ben Bolker, we can change the scatter3d function in R to plot "prettier" (http://stackoverflow.com/questions/8204972/carscatter3d-in-r-labeling-axis-better), however, saving the plot is a trickier. rgl.snapshot saves the image as a png but to save a high resolution image (PDF) rgl.postscript must be used. Using rgl.postscript will not save the image with font/text size/axis sizes as specified (I edited the scatter3d function to increase text/axis sizes). rgl.snapshot works as it should so why doesn't rgl.postscript? Does anyone know an alternative saving method or is there a way to save the plot with larger text/axis etc?
A simple example works for me with the a more recent version of rgl than the CRAN one (CRAN has 0.92.798, r-forge now has 0.92.836, this is with 0.92.829). It looks like versions are numbered by SVN revision, so this is one version after the update mentioned in the comments above ...
library(rgl)
set.seed(1001)
n <- 20
text3d(runif(n),runif(n),runif(n),LETTERS[1:n],cex=seq(0.5,5,length=n))
rgl.postscript(file="tmp.ps")
However, a big warning is that the resulting PS, PDF, files etc. are a bit wonky. The bounding boxes are a little odd, although I could text-edit that manually. ps2pdf and ps2png mangled it .. epstopdf seems to have worked (these are all tools that are available on Linux boxes, don't know about for other OS). In principle rgl.postscript() allows you to export as PDF, but it might be weird PDF ... StackOverflow doesn't recognize the file as being in a valid upload format.
R Under development (unstable) (2012-01-01 r58032)
Platform: i686-pc-linux-gnu (32-bit)
[snip]
other attached packages:
[1] rgl_0.92.829

How to source file.R without output

Is it possible to source a file without printing all the charts etc (already tried with echo=F)?
In my case I call the png("filename%03d.png") device early in the script. It is not to big a hassle to comment this out - but all the charts do take a lot of time to render. (the specific file I am working with now uses base-graphics - but mostly I'll be using ggplot2 - which makes the issue somewhat more important (ggplot2 is excellent, but in the current implementation not the fastest))
Thanks
It's not a problem for ggplot2 or lattice graphics - you always have to explicitly print them when they are called in non-interactive settings (like from within a script).
Good practise for coding R means wrapping as much of your code as possible into functions. (See, e.g., Chapter 5 of the R Inferno, pdf.) If you place your plotting code inside a function, it need not be displayed when you source it. Compare the following.
File foo.r contains
plot(1:10)
When you call source('foo.r'), the plot is shown.
File bar.r contains
bar <- function() plot(1:20)
When you call source('bar.r'), the plot is not shown. You can display it at your convenience by typing bar() at the command prompt.
Perhaps this might be of some help...
"A package that provides a null graphics device; includes a vignette, "devNull", that documents how to create a new graphics device as an add on package. "
from http://developer.r-project.org/
It's not the best sounding solution, but If you might be running this script often like this, you could declare a boolean whether graphics are required (graphics_required=TRUE) and then enclose all your plot commands in if/then clauses based on your boolean, then just change the boolean to change the behaviour of the script

Resources