Making a series of plots that proceed by a click - r

In the example below I would like to be able to control when I go to the next plot by a using mouse click (or keyboard entry)
for (i in 1:5){
plot(1:i)
Sys.sleep(1)
#add something here that requests mouse click to proceed
}
Is this possible? There is a setting in the X11() help file caled 'clickToConfirm' but I can't work out what that does.
It would also be helpful to me to be to be able to scroll back and forth through plots using the arrow keys. Is this possible?
Currently if I need to look at lots of plots I output them into a big .pdf file and scroll though them all there, but that is a bit cumbersome.
Thanks
Tom

In R, that would be done by setting par(ask=TRUE). Try the following code, which shows how to reset the par when exiting the function :
op <- par(ask=TRUE)
for (i in 1:5){
plot(1:i)
}
par(op)
If you want to keep a history to browse through, you can either open a window and click on recording in the History menu, or you can open the window yourself with the history on. Demonstrated in a function :
plot.fun <- function(){
windows(record=TRUE) # opens a window and starts recording
op <- par(ask=TRUE)
on.exit(par(op))
for (i in 1:5){
plot(1:i)
}
windows.options(record=FALSE) #stops recording.
}
plot.fun()
This will however keep all previous plots in the history for browsing as well, so if you run this code 3 times you'll have 15 plots in the plot history. Also note that the open plot window will keep on recording until you turn off the recording in the menu.
You can play with the plot history, as you'll have a variable .SavedPlots which contains the saved plot history. It can be cleared using the menu History > clear history in the plot window. If you want to clear the history from the console, you could hack that by
.SavedPlots <- NULL
But I advise you not to do this, as changing the .SavedPlots variable can cause R to crash.
See also ?windows and ?recordPlot for a bit more information. But as you're getting close to the internal code of R, be warned that you can get pretty awkward behaviour if you start playing around with these things.

For scrolling back and forth between plots using the arrow keys: it depends on the platform/R interface.
Windows: there is a recording function (see Q5 of the R for Windows FAQ) which uses Page Up/Page Down
MacOS: under the standard GUI, the Quartz window has Apple-left and Apple-right arrow
under the standard Unix (no-GUI) interface, things are more limited. You can use RStudio (which has a lot of buzz right now) ... I would have thought that JGR would have plot history as well, but it doesn't seem to ...

You can use locator - now plots change on click
for (i in 1:5){
plot(1:i)
locator(1)
}

Related

RStudio: Get Size of Plot Zoom Window Programmatically

grDevices::dev.size() programmatically provides the size of the Viewer pane in RStudio.
Is there a similar command (or maybe even a hack) for programmatically obtaining the size of the Zoom window? A brief search of the rstudioapi commands doesn't seem to offer any leads.
It has been a long time since I've been stuck with a similar problem. Have you found the answer?
I went with this solution:
Start with window
}
x11() # open new window
boxplot(rnorm(100)) # wrtie some good box full of normal values.
#Plot it! You will see it on the new screen.
#Now, let's make this loop, and everything will appear.
while(TRUE){
cdev <- grDevices::dev.size("cm")
Sys.sleep(0.5)
cat("Width (cm):", cdev[1], "High (cm):", cdev[2], "\r")
cat("Press escape to break it.")
}
#Change the new windows number size, and those new numbers will flow.

Using GoogleVis in R inside Power BI

I am trying to replicate these:
https://radacad.com/interactive-map-using-r-and-power-bi-create-custom-visual-part-1
Is it possible to use R Plotly library in R Script Visual of Power BI?
The issue with Plotly is that for my dataset it is so slow even when I am compiling that in R. takes several minutes. So, I have decided to replace it with googleVis which is really fast (I am open any other interactive Gantt Chart in R).
Here is my code in R:
df <- data.frame(Values)
library("googleVis")
#df$Project.Name <- toString(df$Project.Name)
df$Processed_start_date_cut <- as.Date(df$Processed_start_date_cut)
df$Processed_End_date <- as.Date(df$Processed_End_date)
#df$Milestone <- toString(df$Milestone)
g <- gvisTimeline(data=df,
rowlabel="Project.Name",
barlabel="Milestones",
start="Processed_start_date_cut",
end="Processed_End_date",
options=list(timeline="{rowLabelStyle:{fontName:'Helvetica',
fontSize:10, color:'#603913'},
barLabelStyle:{fontName:'Garamond',
fontSize:12}}",
backgroundColor='#ffd',
height=350 ))
cat(g$html$chart, file="out.html")
I have tried it in R and it works great. In BI this works for the first time, but when I change any filters, nothing shows up in this newly developed pbivis item unless I go to another tab of my report and then come back to this tab which has this newly developed pbivis (this was the reason I thought it is not working at first, sorry).
See the screenshot
I have also noticed that if I maximize this item (pbivis), then the chart disappears (i.e. shows nothing).
I guess I need a kind of code for refreshing the visuals which possibly can come before df <- data.frame(Values), maybe something like F5 in IE.
Also tried this and did not work:
if (file.exists("out.html"))
#Delete file if it exists
file.remove("out.html")
As user3867743 suggested, the issue is related to
cat(g$html$chart, file="out.html")
After replacing it by
print(g, file="out.html")
It has started working fine.

R Need to restart RStudio to view and save in a file using dev.copy() and dev.off()

I am trying to create a plot and eventually save it as a file. But because I am making a lot of changes and want to test it out, I want to be able to view and save the plot at the same time. I have looked at this page to do what I want to do but in my system, it does not seem to be working as it is supposed to.
Here are my codes:
png('Save.png')
sample.df <- data.frame(group = c('A','B','A','C','B','A','A','C','B','C','C','C','B'),
X = c(2,11,3,4,1,6,3,7,5,9,10,2,8),
Y = c(3,8,5,2,7,9,3,6,6,1,3,4,10))
plot(Y ~ X, data = sample.df)
dev.copy(png, 'Save.png')
dev.off()
There are several issues (I am new to R so I might be missing something entirely):
(1) When I use png(), I cannot view the plot in RStudio so I used dev.copy() but it does not allow me to view my plot in R studio
(2) Even after I use dev.off(), I cannot view the saved file until I close the RStudio (says "Windows Photo Viewer can't open this picture because the picture is being edited in another program"). I need to restart every time so it is very inconvenient.
What am I doing wrong and how could I view and view saved file without restarting RStudio every time? Thank you in advance!
Addition
Based on Love Tätting's comments, when I run dev.list(), this is what I get.
> png('Save.png')
>
> sample.df <- data.frame(group = c('A','B','A','C','B','A','A','C','B','C','C','C','B'),
+ X = c(2,11,3,4,1,6,3,7,5,9,10,2,8),
+ Y = c(3,8,5,2,7,9,3,6,6,1,3,4,10))
>
> plot(Y ~ X, data = sample.df)
>
> dev.copy(png, 'Save.png')
png
3
> dev.off()
png
2
> dev.list()
png
2
> dev.off()
null device
1
> dev.list()
NULL
Why do I not get RStudioGD?
RStudio has its own device, "RStudioGD". You can see it with dev.list(), where it by default is the first and only one.
R's design for decoupling rendering and backend is by the abstraction of devices. Which ones you can use is platform and environment dependent. dev.list() shows the stack of current devices.
If I understand your problem correctly you want to display the graph first in RStudio, and then decide whether you want to save it or not. Depending on how often you save th image you could use the 'export' button in the plot pane in RStudio and save it manually.
Otherwise, your choice of trying to copy it would be the obvious one for me as well.
To my knowledge the device abstraction in R does not allow one to encapsulate the device as an object, so one for example could make it an argument to a function that does the actual plot. Since dev.set() takes an index as argument, passing the index as argument will be dependent on state of the stack of devices.
I have not come up with a clean solution to this myself and have sometimes retorted to bracketing the plot rendering code with a call to a certain device and saving it right after, and switching device depending on a global.
So, if you can, use RStudios export functionality, otherwise an abstraction would need to maintain the state of the global stack of devices and do extensive testing of its state as it is global and you cannot direct a plot call to a certain device, it simply plots to the current device (to my knowledge).
Edit after OP comment
It seems that it is somewhat different behaviour you are experiencing if you cannot watch the file after dev.off, but also need to quit RStudio. For some type of plot frameworks there is a need to call print on the graphical object to have it actually print to the file. Perhaps this is done by RStudio at shutdown as part of normal teardown procedures of open devices? In that ase the file should be empty if you forcibly look in its contents before quiting RStudio.
The other thing that sometimes work is to call dev.off twice. I don't know exactly why, but sometimes more devices get created than I have anticipated. After you have done dev.off, what does dev.list show?
Edit after OP's edit
I can see that you do, png(); dev.copy(); dev.off(). This will leave you with one more device opened than closed. You will still have the first graphics device that you started open as can be seen when you do the listing. You can simply remove dev.copy(). The image will be saved on dev.off() and should be able to open from the filesystem.
As to why you cannot see the RStudio graphics device, I am not entirely sure. It might be that other code is messing with your device stack. I would check in a clean session if it is there to make sure other code isn't tampering with the device stack. From RStudio forums and other SO questions there seem to have been plot pane related problems in RStudio that have resolved after updating RStudio to the latest. If that is a viable solution for you I would try that.
I've just added support for RStudio's RStudioGD device to the developer's version of R.devices package (I'm the author). This will allow you to do the following in RStudio:
library("R.devices")
sample.df <- data.frame(
group = c('A','B','A','C','B','A','A','C','B','C','C','C','B'),
X = c(2,11,3,4,1,6,3,7,5,9,10,2,8),
Y = c(3,8,5,2,7,9,3,6,6,1,3,4,10)
)
figs <- devEval(c("RStudioGD", "png"), name = "foo", {
plot(Y ~ X, data = sample.df)
})
You can specify any set of output target types, e.g. c("RStudioGD", "png", "pdf", "x11"). The devices that output to file will by default write the files in folder figures/ with filenames as <name>.<ext>, e.g. figures/foo.png in the above example.
The value of the call, figs, holds references to all figures produced, e.g. figs$png. You can open them directly from R using the operator !. For example:
> figs$png
[1] "figures/foo.png"
> !figs$png
[1] "figures/foo.png"
The latter call should show the PNG file using your system's PNG viewer.
Until I submit these updates to CRAN, you can install the developer's version (2.15.1.9000) as:
remotes::install_github("HenrikBengtsson/R.devices#develop")

Rstudio -- graphics locator() gets stuck under manipulate()

I'm QC-ing a large dataset using RStudio. I'm viewing chunks of it using a graphics montage made using regular R graphics, with some manipulate() controls to control the subsetting. When I see something funny on a display, I want to pick some XY coordinate pairs (NOT data points, but in the same space), hit the Finish button provided by locator() to capture my picks, then go back to browsing. In this way I am building up a set of picked XY locations for further processing.
So my manipulate() controls are mostly subsetting parameters, but I also have a button called Pick Points to enter locator() mode.
This almost works, but when I hit Finish to terminate locator(), things don't quite work right. locator() finishes and returns a list of coordinate arrays as expected, but the graphics display stays in locator() crosshair mode and the Finish button persists. Any further clicks or Finish button clicks provoke an error popup Method not found.
I can right-mouse on the graph and Reload to reset things without hurting the running program or my saved data, but it's a bit distracting.
Here's a minimal example that provokes the bug.
demonstrateBug <- function() {
manipulate(
{
if( pickData ){
locData <- locator()
nPoint <- length( locData$x )
message( " ... Picked ", nPoint, " points" )
} else {
plot( runif(10), runif(10) )
}
},
pickData = button("Pick Points")
)
}
I've tried Google but there are very few references to the specific combination of manipulate() and locator(), and nothing about a bug like this.
locator() works OK from the RStudio console when run against a manipulate()-enhanced graphics plot, but that won't do what I want.
If I give locator() a fixed number of points, it returns on cue, but the cross-hairs and button still persist. I don't want a fixed number of points, anyway.
Running R 3.1.2 RStudio 0.99.441 on OSX Yosemite
(I've never asked for help on this platform before, so I hope this all comes out right!)

R - Keep log of all plots

I do a lot of data exploration in R and I would like to keep every plot I generate (from the interactive R console). I am thinking of a directory where everything I plot is automatically saved as a time-stamped PDF. I also do not want this to interfere with the normal display of plots.
Is there something that I can add to my ~/.Rprofile that will do this?
The general idea is to write a script generating the plot in order to regenerate it. The ESS documentation (in a README) says it well under 'Philosophies for using ESS':
The source code is real. The objects are realizations of the
source code. Source for EVERY user modified object is placed in a
particular directory or directories, for later editing and
retrieval.
With any editor allows stepwise (or regionwise) execution of commands you can keep track of your work this way.
The best approach is to use a script file (or sweave or knitr file) so that you can just recreate all the graphs when you need them (into a pdf file or other).
But here is the start of an approach that does the basics of what you asked:
savegraphs <- local({i <- 1;
function(){
if(dev.cur()>1){
filename <- sprintf('graphs/SavedPlot%03d.pdf', i)
dev.copy2pdf( file=filename )
i <<- i + 1
}
}
})
setHook('before.plot.new', savegraphs )
setHook('before.grid.newpage', savegraphs )
Now just before you create a new graph the current one will be saved into the graphs folder of the current working folder (make sure that it exists). This means that if you add to a plot (lines, points, abline, etc.) then the annotations will be included. However you will need to run plot.new in order for the last plot to be saved (and if you close the current graphics device without running another plot.new then that last plot will not be saved).
This version will overwrite plots saved from a previous R session in the same working directory. It will also fail if you use something other than base or grid graphics (and maybe even with some complicated plots then). I would not be surprised if there are some extra plots on occasion that show up (when internally a plot is created to get some parameters, then immediatly replaced with the one of interest). There are probably other things that I have overlooked as well, but this might get you started.
you could write your own wrapper functions for your commonly used plot functions. This wrapper function would call both the on-screen display and a timestamped pdf version. You could source() this function in your ~/.Rprofile so that it's available every time you run R.
For latice's xyplot, using the windows device for the on-screen display:
library(lattice)
my.xyplot <- function(...){
dir.create(file.path("~","RPlots"))
my.chart <- xyplot(...)
trellis.device(device="windows",height = 8, width = 8)
print(my.chart)
trellis.device(device = "pdf",
file = file.path("~", "RPlots",
paste("xyplot",format(Sys.time(),"_%Y%m%d_%H-%M-%S"),
".pdf", sep = "")),
paper = "letter", width = 8, height = 8)
print(my.chart)
dev.off()
}
my.data <- data.frame(x=-100:100)
my.data$y <- my.data$x^2
my.xyplot(y~x,data=my.data)
As others have said, you should probably get in the habit of working from an R script, rather than working exclusively from the interactive terminal. If you save your scripts, everything is reproducible and modifiable in the future. Nonetheless, a "log of plots" is an interesting idea.

Resources