PgDn and PgUp Keys in R Graphics Viewer - r

I've never been able to figure out how to get the PgDn/PgUp keys to work in the R Graphics Viewer.
Even the demo() programs don't seem to support it.
Anyone able to point me to some code that shows how this can be implemented?

Dirk is right.
Another thing to look at are the following functions:
x <- recordPlot()
replayPlot(x)
From the R for Windows FAQ:
The graphics has a history mechanism. As README.R-2.9.2 says:
The History menu allows the recording of plots. When plots have been recorded they can be reviewed by and , saved and replaced. Recording can be turned on automatically (the Recording item on the list) or individual plots can be added (Add or the key). The whole plot history can be saved to or retrieved from an R variable in the global environment. The format of recorded plots may change between R versions. Recorded plots should not be used as a permanent storage format for R plots.
There is only one graphics history shared by all the windows devices.
The R console and graphics windows have configuration files stored in the RHOME\etc directory called Rconsole and Rdevga; you can keep personal copies in your HOME directory. They contain comments which should suffice for you to edit them to your preferences. For more details see ?Rconsole. There is a GUI preferences editor invoked from the Edit menu which can be used to edit the file Rconsole.

As I recall you have to turn 'recording' or 'History' on. This is platform-specific and I am not near a Windows machine.

On a mac, one can use the command key with the back arrow (and forward arrow) to cycle through plots.
Make sure you've plotted at least two plots to the same quartz device, then with the plotting window in focus, hit ⌘ ← to see the previous plot.

Related

How do I conveniently resize a ggplot2 plot on R+VSC?

I'm in the process of learning R (I'm still a newcomer on SO as well). Being very used to using Visual Studio Code, I decided to choose that over RStudio or RStudio Cloud.
One of the best parts of RStudio was that plots automatically resized/reshaped themselves if we resized the right pane. Moreover, in the tutorials I watched, plots involving map data automatically rendered in the correct aspect ratio (as seen on physical maps).
I replicated the code to make my own plot of the world map. Unfortunately it rendered as a square shape, and resizing the right pane does not affect its shape:
enter image description here
Am I missing any commonly used VSC extensions which can make plots resizeable like in RStudio? (I've installed only the most downloaded extension for R, by Yuki Ueda)
If not, can I modify my code to specify the exact dimensions I need the plot to have?
Thanks in advance!
You can add robust plot viewing options for R in VSCode by installing the httpgd package and then amending your JSON settings.
First, install httpgd via the R console:
install.packages("httpgd")
Then, open your JSON settings in VSCode by opening the Command Palette (either via Ctrl+Shift+P or via View > Command Palette) and then searching for "Preferences: Open Settings (JSON)", where you'll insert the following:
"r.plot.useHttpgd": true
You can add a comma after 'true' if needed (i.e. if there are other lines below that in your JSON settings).
Following that, restart VSCode and launch the R terminal inside it, and plot something using either ggplot2 or base R graphics:
plot(mtcars$mgp, mtcars$wt)
A plot viewer should then pop up in VSCode. You can either manually resize the window there, zoom in or out, or, my preference (particularly if I'm cycling through a series of already-plotted graphs), open it in an external browser where it'll automatically adjust to however you resize the window. After that, you can save or copy the image as needed.
You can specify the dimensions when you save the file. I usually use (approximately) the golden ratio:
ggsave("./earth.png", width = 16, height = 10)
The ggsave function reference explains how you can change units - options are c("in", "cm", "mm", "px").

How to send commands to R in ESS

I, an R user, decided recently to try using Emacs-ESS combo. So far I have been work in a single-window mode (C-x 1) just for text highlighting.
Now I am trying split it in two windows (C-x 3) to work on an .R file in the left window, and have R execute the commands in the right window. Something like this:
After selecting sections of code on the left, how can I "send" it as a command to the right? Essentially, I want the input to remain on on the left (so that I can incrementally build the code up) and the actual R output on (including error messages) the right.
Two good options:
ess-eval-region-or-function-or-paragraph vis
(C-M-x): Sends the current selected region or function or paragraph.
ess-eval-region-or-function-or-paragraph-and-step (C-c C-c): Like ess-eval-region-or-function-or-paragraph but steps to next line of code.
Source: ESS manual.
You can also use:
C-c-p to send a paragraph or region between two empty lines
C-c-r to send a region that has been selected and is highlighted
I prefer this way because you only need to press the Ctrl key
there are normally many ways to send code to the R console. It will take you time to realize what is best for you, or you may eventually change the key bindings.

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.

Using jpeg(file= ) creates an empty jpeg even though there's not a call to create a plot

This is observed running in batch. Given the following code snippet, I don't understand why R creates an empty jpeg file in Windows even though I am not calling a plot or graph. When I run similar code under Linux or OS X, the jpeg file is not created. I don't know ahead of time if the user is going to want a plot so I setup the filename(s) ahead of time and give them a name and location.
##
sink("c:\\temp\\test.lst")
jpeg(file="c:\\temp\\test%d.jpeg")
norm <- rnorm(100)
print(norm)
Any suggestions would be appreciated.
The ?jpeg help file (which also applies to bmp(), png() and tiff() devices) indicates that:
The ‘type = "windows"’ versions of these devices effectively plot
on a hidden screen and then copy the image to the required format.
This Windows-specific implementation detail most likely explains the difference in the behavior of Windows and *NIX systems.
On Windows, calling any of the functions above (and pdf() and postscript() as well) creates a file --- whether or not you then plot anything to that hidden screen. Except for pdf() (which produces files that I can't open with a viewer), the image that's registered on the plotting device is that of a white rectangle of height and width specified in the call to the specific device.
I wouldn't worry about it. if the prospect of zero-length files cluttering up the folder bothers you, you can clean up afterwards with something like
jpgs <- file.path("c:/temp", dir(pattern="c:/temp/test[0-9]*\\.jpeg"))
s <- file.info(jpgs)[["size"]]
for(i in seq_along(s))
if(s[i] == 0) file.remove(jpgs[i])

Disable GUI, graphics devices in R

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")

Resources