Save a package specific plot to pdf R - r

I use the package esd (see reproductible code below) which is climatology package.
The package has several custom map() and plot() functions.
I save my plots to Pdf's. map() function work well doing:
x<-my.field.object
CairoPDF(file="/path/to/file.pdf")
map.field(x)
dev.off()
However plot doesn't work. Doing the same code as above, it will actually plot (with x11()) in Rstudio and nothing will be output to the pdf file.
I tried looking inside the function but can't see anything that make it behave like that.
Any idea?
P.S: for those who would like to try, the package has some field data in it, for example
Reproducible code:
#devtools::install_github("metno/esd")
library("Cairo")
x<-t2m.NCEP(lon=c(-40,40),lat=c(30,70))
CairoPDF(file="/path/to/file.pdf")
plot.field(x)
dev.off()
EDIT: I'm aware of the dev.print solution. It works, but the problem is that i actually need to put several plot.field into one PDF file.

Related

How to render qcc plots to HTML using RMarkdown and knitr

First SO question so please go easy.
I am running the qcc package with Rstudio and I would like to create a report on the graphs that I am generating. I have no problem generating the graphs and exporting each individual graph to pdf for example. I also have no problem creating a HTML document with RMarkdown and Knitr with other plots.
However, with qcc package, I cannot do this! Hopefully someone out there has had this issue and solved.
Here is example from ?qcc that can be used in an RMarkdown file with the issue I am seeing:
data(pistonrings)
attach(pistonrings)
diameter <- qcc.groups(diameter, sample)
qcc(diameter[1:25,], type="xbar")
qcc(diameter[1:25,], type="xbar", newdata=diameter[26:40,])
q <- qcc(diameter[1:25,], type="xbar", newdata=diameter[26:40,], plot=FALSE)
plot(q, chart.all=FALSE)
Thanks in advance for support.
So, I found the reason for this eventually. When function dev.off() is called in the Rmarkdown file then the base plot function will not work!...I didn't include the dev.off() in my question as it was at the top of my script and I hadn't spotted it.
Sorry for the confusion and I hope this helps somebody else.

R markdown, hiding the library output

I am working on a rmarkdown presentation. I am trying to show the usage of cast function. However, since the reshape package is necessary, to run the cast function, I need to load reshape library as below.
{r package_options, echo=TRUE}
library(reshape)
cast(datam, isim~Ay, value="Sirano")
However, after knitting the codes, I face with the output ;
I just need to see the name of the library on the screen which is library(reshape) , and also I want it to be used to run cast function, but I dont want to see the package outputs as shown in the picture.
Would someone help about that?
If you want to hide all these messages you have to put :
```{r,warning=FALSE,message=FALSE}
library(reshape)
```

R effects plot displays OK on screen but generated pdf contains no pages

I am using the effects package in R to derive (and plot) the effects of a complicated linear model.
When I use allEffects(linearModel) I can see the results on screen and save it to a pdf file as usual. Since the model has many terms, the output is not useful as it stands.
Therefore I use effects(someTerm, linearModel) to focus on the terms of interest and the results on screen are what I need. However, when saving it to a pdf file, the file contains no useful output (though it does take up 3.5Kb of space). There is no error message from R at the console.
To ease understanding, I created a simple data set and a script for generating the effects plots, in the same way that I tried with the "real" model.
factorData.csv
A,B,C,y
a1,b1,c1,3
a1,b2,c1,4
a2,b1,c1,5
a2,b2,c1,6
a1,b1,c1,2
a1,b1,c2,3.5
a1,b2,c2,4
a2,b1,c2,5.1
a2,b2,c2,6.2
plotEffect.r
require(effects)
dataFile <- '/tmp/factorData.csv'
effectABfile <- '/tmp/effect_AB.pdf'
effectABCfile <- '/tmp/effect_ABC.pdf'
allEffectFile <- '/tmp/lm_eff.pdf'
df <- read.csv(file=dataFile,header=TRUE,sep=',')
linearModel <- lm(y~A*B*C,data=df)
lm_eff <- allEffects(linearModel)
pdf(file=effectABfile)
plot(effect('A:B',linearModel))
dev.off()
pdf(file=allEffectFile)
plot(lm_eff)
dev.off()
pdf(file=effectABCfile)
plot(Effect(c('A','B','C'),linearModel))
dev.off()
As you can see, I tried allEffects, effect and Effect; allEffects is the only one that works for me. Please note that the script assumes that the data is placed in /tmp/factorData.csv - you might need to change the path of course. I also randomised the order in which the plots are generated, with no effect.
I had a look elsewhere on stackoverflow and saving plots to pdfs fails was the closest but the advice there (to issue dev.off() after each plot to 'close' the pdf file) is something I do already, as seen in plotEffect.r.
I tried this script on 2 machines, each running Lubuntu 14.04.1 64-bit with R version 3.0.2 and the latest effects package installed within R using install.packages. The results were the same.
I would be very grateful for advice on how to fix the problem of saving (instances of) this plot type to a pdf.
Fix/workaround
As suggested by #Roland in the comments below, if you wish to save grid plots (such as the output from the effects plots in this instance) into pdf files, it is better/more reliable to generate the plots separately/manually (rather than in a script). It does not appear to be (as much of) an issue for base graphics or even ggplot2 graphics, where I for one have never encountered this problem/needed this workaround in the past. Thanks to #Roland for suggesting this fix!
#Roland also added that Sys.sleep() might help in scripts. Although it did not do so in my case, I discovered that it was possible to paste several such plotting commands and R would run them as a batch, saving the plots to pdf correctly. Therefore, I believe it should be possible to recover much of the benefits of running the script by taking these steps:
Use R to create the text representation of the pdf(), plot() and dev.off() triad of commands
The main script outputs this plotting command text (specific to each instance of a plot) to a file
Open the plotting command text in a text editor
Copy the entire contents of the commands file and paste it into the R console
Optionally, you may wish to use the command line in Step 3 and 4 - How can I load a file's contents into the clipboard? has useful advice.
This two stage procedure is a reasonable workaround, but arguably there should be no need for it.

issues of wrapping up a set of workable R commands into a function

I generate a dendrogam using a collection of r commands. It worked just fine and saved the generated dendromgram into a PDF file. To improve efficiency, I wrapped these commands as a function, which does not change anything. However, the pdf is just a blank file without any graphical content. Please let me know what’s wrong with my function defintion. Thanks.
myplot<-function(inputcsv, outputfile){
library(ggdendro)
library(ggplot2)
x<-read.csv(inputcsv,header=TRUE)
d<-as.dist(x,diag=FALSE,upper=FALSE)
hc<-hclust(d,"ave")
dhc<-as.dendrogram(hc)
ddata<-dendro_data(dhc,type="rectangle")
ddata$labels$text <- gsub("\\."," ",ddata$labels$text)
ggplot(segment(ddata))+geom_segment(aes(x=x0,y=y0,xend=x1,yend=y1))
pdf(outputfile, width=30,height=35)
last_plot()
dev.off()
}
R FAQ
Wrap your ggplot call in a print() function.
ggplot and friends return an object, and the plotting only happens when the object is printed. When you do this on the command line the printing happens automatically. When you stick it in a script or function you have to do it yourself.
The debate on whether this is a good idea or a dumb thing that just generates questions like this continues...

sweave and ggplot2: no pdfs generated at all

I am trying create a sweave report that contains some graphics done with ggplot2. Though I am looking for some environment for the long run – I just use a simple .Rnw file here that only contains the code and the plot
\documentclass[a4paper]{article}
\SweaveOpts{echo=FALSE}
\usepackage{a4wide}
\begin{document}
\begin{figure}[htbp]
\begin{center}
<<>>=
library(ggplot2)
x=rnorm(100)
qplot(x)
#
\caption{My Graph}
\end{center}
\end{figure}
\end{document}
Unfortunately the graph is not created, I only get a corrupted .pdf and .eps file. Though I get a nice .tex file that appears to work except for the graphics.
I use the following basic code to create it:
Sweave("myfile.Rnw")
I just found some older post on the web that were discussing problems with transparency and sweave / ggplot2 but nothing that could have helped. I also tried the relaxed package, which did not help either. Btw, is there any news on decumar package?
qplot() produces objects, not a graphic output. It might seem like it does when you run it, but that's because without assignment, R is automatically printing the output of qplot(). To integrate it into Sweave, either wrap print() around qplot(), or assign the output of qplot() to something, then wrap that in print().
...
<<fig = T, echo = F>>=
library(ggplot2)
x=rnorm(100)
p <- qplot(x)
print(p)
#
...
That should work. I use ggplot2 graphics in my sweave docs all the time.
You have to wrap it around print() to make it work in sweave.
Actually, while both previous answers are correct, your problem is something else.
You need to ensure that the entire code block is at the left of the page (apart from iundentation in functions). Again, I have no idea why but this causes problems for Sweave.
After ensuring that all code (and header/footer for code chunk) were at the left of the page (and adding a print statement) then your example works for me.
Incidentally, i learned today that you can create an environment around your code in sweave documents (which i wasn't aware of, and will save me much time). Good old stackoverflow, teaching you something new even when you answer a question!
Hope this helps.

Resources