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")
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!)
I am executing some R scripts with a source() command and then flushing the console. The only thing that I want visible in the console is some text with a progress report of the script, after that some progress bars are displayed, all the rest of the code is hidden. I am printing my progress report to the console by manually adding the text using the cat() function as below.
cat("\014")
cat(" =====================================\n")
cat(" ========== PROGRESS REPORT ==========\n")
cat(" =====================================\n")
cat("\n")
# progress bar implementation
What I was wondering: Is there a way to center the text automatically in the middle of the console so that it adjusts dynamically when you resize the window size of the console? I am looking for a way that works both in R Studio and also baseR in Windows and Mac OS X.
You could try something like this. This may or may not be exactly centered, it depends on the current console width (which is floored if an odd number occurs in the calculation of p).
centerText <- function() {
width <- getOption("width")
out <- "=======================================\n"
mid <- "=========== PROGRESS REPORT ===========\n"
ws <- rep(" ", floor((width - nchar(out))/2))
cat(ws, out, ws, mid, ws, out, sep = "")
}
centerText()
It works in RStudio, but I'm not sure if it works in the normal R console. Might need some tweaking.
So i have done an entire gwidget script which creates the GUI for running my scripts .
win <- gwindow("TITLE HERE",height=500,weight=500)
However it seems that whenever i maximize the window, or elongate the window size by dragging it, it breaks and the size doesn't fix anymore.
Any idea how to force the window to not be able to resize ? or a permanent way to fix the size.
Here is an image of my situation
http://imgur.com/cEtU773
I'm also using gwidgets and gwidgetscltk package
I think is not possible using gwidgets. You can set andle a "resize event or signal".
One alternative is to use RGtk2 (GTK+ 2.0):
library(RGtk2)
win <- gtkWindow("toplevel", show = FALSE)
gtkWidgetSetSizeRequest(win, 500, 500)
win$show()
gtkWindowSetResizable(win, FALSE)
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)
}