I have a simple R script doing:
jpeg(myplot.jpg)
x<-seq(1,20,0.1)
y<-sin(x)
plot(x,y)
dev.off()
After execution it makes a myplot.jpg file in /root/work/ but renders gibberish information and does not plot a legible graph.
Also how can I view the graph in R shell itself?
The first argument to jpeg should be a character string, so I wouldn't expect your code to work unless myplot.jpg contained a character string. This works fine for me:
jpeg("myplot.jpg")
x<-seq(1,20,0.1)
y<-sin(x)
plot(x,y)
dev.off()
Whether you can view the graph in the "shell" depends on the R console you're using. If you're running R from bash, sh, etc, the answer is "no, you can't view a plot directly"... actually it wouldn't surprise me if there was a package that allowed you to create text-plots, but I don't think that's what you want.
Related
I use org.rosuda.jri lib to run an R script that implements the ordinary kirging algorithm via java. I use ubuntu 13.04 and the version 1.7-3 of REngine While all the results are perfectly produced BUT i can not create the plots and store them.
while the following lines are perfectly executed in R console
png('/home/panisis/Desktop/plots/tralala.png');
spplot(df);
dev.off();
These ones are ignored
re.eval("png('/home/panisis/Desktop/plots/tralala.png');");
re.eval("spplot(df);");
re.eval("dev.off();");
What i am missing???
Thanks for the dedicated time. :-)
i just found the answer myself. i put it here for next users. i had to assign the plot to a temporary variable (like temp <- spplot()) and then use print(temp) to save it as png file for example temp <- spplot() png(filename="pathToFile") print(temp) dev.off()
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.
Does anyone know why savePlot can't save to pdf in linux by default?
> savePlot("rv-3.pdf", type="pdf")
Error in match.arg(type) :
'arg' should be one of “png”, “jpeg”, “tiff”, “bmp”
lizard:~images$ R --version
R version 2.14.1 (2011-12-22)
...
?savePlot is pretty clear about this:
This works by copying the image surface to a file.
Hence you start with a raster representation and therefore can only go to a raster representation. It would be somewhat perverse to pipe a raster version of the plot in a PDF, which is a vector format (yes I know you can have rasters inside PDFs).
The functionality is limited to cario-based X11 devices and the documentation refers to copying the "on screen" representation hence the restrictions.
I suppose the other Answer to your question is: that functionality has not been implemented yet.
dev.copy2pdf does what you want:
plot(1:10)
dev.copy2pdf(file="~/test.pdf")
From reading the help files, I take it this will effectively replot your figure as a vector image in the file, which will usually be preferable to exporting your vector image into a raster format, as savePlot appears to do.
Try this:
pdf(file="rv-3.pdf")
plot(x,y)
dev.off()
you can also change the size by by adding height= or width= to the pdf 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...
Is there an easy way to turn of all GUI elements in R and run it solely from the command line on OSX?
I'm trying to replicate the behavior of a remote linux terminal on my OSX machine. Thus plot() should just save a file and things like CRAN mirror selection should be text, not a Tk interface. I'm having trouble finding where to set this behavior.
I had this exact question and wanted a way to do it without changing my existing code. I usually run with graphics support but sometimes I'll run a script on the server for a larger dataset and then I just want the plots to be output somewhere automatically.
In Dirk's answer Ian Fellows gives the simple solution. On the command line in R type:
options(device=pdf)
And then any plots will be written to the current directly to an Rplots.pdf file.
If you want the files to not be plotted at all then use
options(device=NULL)
For the plots you can just direct the output to a file using the pdf() command (or png(), jpeg()...).
I don't own an OS X box, but did you try to unset the X11 environment variable DISPLAY:
DISPLAY="" R --vanilla
When I do that on Linux and query R for capabilties(), x11 comes up as FALSE as desired.
I don't run OSX but you could attempt to run R from the Terminal application, rather than the Mac OSX launcher, and see whether that runs as you need.
As Matti writes, you can send output to files using the following commands; but I don't know if that's really the substance of your question.
png("pngfile.png")
plot(foo)
title(main="bar")
dev.off()
So instead of the quartz graphical object, your output goes to the file.
Similarly, you can output what would normally appear in the terminal to a file.
sink("foo.file")