Save a plot in an object - r

In ggplot2, one can easily save a graphic into a R object.
p = ggplot(...) + geom_point() # does not display the graph
p # displays the graph
The standard function plot produces the graphic as a void function and returns NULL.
p = plot(1:10) # displays the graph
p # NULL
Is it possible to save a graphic created by plot in an object?

base graphics draw directly on a device.
You could use
1- recordPlot
2- the recently introduced gridGraphics package, to convert base graphics to their grid equivalent
Here's a minimal example,
plot(1:10)
p <- recordPlot()
plot.new() ## clean up device
p # redraw
## grab the scene as a grid object
library(gridGraphics)
library(grid)
grid.echo()
a <- grid.grab()
## draw it, changes optional
grid.newpage()
a <- editGrob(a, vp=viewport(width=unit(2,"in")), gp=gpar(fontsize=10))
grid.draw(a)

I am very late to this, but it was the first question which showed up when I searched for the question. So I'd like to add my solution for future viewers who come across the question.
I solved this by using a function instead of an object. For example, suppose we want to compare two beta distributions with different parameters. We can run:
z1<-rbeta(10000,5,5)
z2<-rbeta(10000,20,20)
plotit<-function(vector,alpha,beta){
plot(density(vector),xlim=c(0,1))
abline(v=alpha/(alpha+beta),lty="longdash")
}
And save the plots as functions rather than objects.
z.plot1<-function(){plotit(z1,5,5)}
z.plot2<-function(){plotit(z2,20,20)}
Next, we can call each plot as we want by simply calling the two plots as functions rather than objects.
z.plot1()
plots the first plot and
z.plot2()
plots the second.
Hope that helps someone who stumbles across this later!

You can use the active binding feature of the pryr package if you don't want to directly change the values of the object created.
library(pryr)
a %<a-% plot(1:10,1:10)
Each time you type a on the console the graph will be reprinted on the screen. The %<a-% operator will rerun the script every time (in case of one graph this is not a problem I think). So essentially every time you use a the code will be rerun resulting in your graph which of course you can manipulate (overlay another plot on top) or save using png for example. No value itself will be stored in a however. The value will still be NULL.
I don't know if the above is what you are looking for but it might be an acceptable solution.

library(ggplot2)
# if mygraph is a plot object
ggsave("myplot1.png",mygraph)
# if the plot is in a list (e.g. created by the Bibliometrics package)
ggsave("myplot1.png",mygraphs[[1]])

Related

Converting a NULL Picture Value to an Object in R [duplicate]

In ggplot2, one can easily save a graphic into a R object.
p = ggplot(...) + geom_point() # does not display the graph
p # displays the graph
The standard function plot produces the graphic as a void function and returns NULL.
p = plot(1:10) # displays the graph
p # NULL
Is it possible to save a graphic created by plot in an object?
base graphics draw directly on a device.
You could use
1- recordPlot
2- the recently introduced gridGraphics package, to convert base graphics to their grid equivalent
Here's a minimal example,
plot(1:10)
p <- recordPlot()
plot.new() ## clean up device
p # redraw
## grab the scene as a grid object
library(gridGraphics)
library(grid)
grid.echo()
a <- grid.grab()
## draw it, changes optional
grid.newpage()
a <- editGrob(a, vp=viewport(width=unit(2,"in")), gp=gpar(fontsize=10))
grid.draw(a)
I am very late to this, but it was the first question which showed up when I searched for the question. So I'd like to add my solution for future viewers who come across the question.
I solved this by using a function instead of an object. For example, suppose we want to compare two beta distributions with different parameters. We can run:
z1<-rbeta(10000,5,5)
z2<-rbeta(10000,20,20)
plotit<-function(vector,alpha,beta){
plot(density(vector),xlim=c(0,1))
abline(v=alpha/(alpha+beta),lty="longdash")
}
And save the plots as functions rather than objects.
z.plot1<-function(){plotit(z1,5,5)}
z.plot2<-function(){plotit(z2,20,20)}
Next, we can call each plot as we want by simply calling the two plots as functions rather than objects.
z.plot1()
plots the first plot and
z.plot2()
plots the second.
Hope that helps someone who stumbles across this later!
You can use the active binding feature of the pryr package if you don't want to directly change the values of the object created.
library(pryr)
a %<a-% plot(1:10,1:10)
Each time you type a on the console the graph will be reprinted on the screen. The %<a-% operator will rerun the script every time (in case of one graph this is not a problem I think). So essentially every time you use a the code will be rerun resulting in your graph which of course you can manipulate (overlay another plot on top) or save using png for example. No value itself will be stored in a however. The value will still be NULL.
I don't know if the above is what you are looking for but it might be an acceptable solution.
library(ggplot2)
# if mygraph is a plot object
ggsave("myplot1.png",mygraph)
# if the plot is in a list (e.g. created by the Bibliometrics package)
ggsave("myplot1.png",mygraphs[[1]])

plotting polygons inside loop in R, why this ambiguous behavior?

So, I want to plot multiple polygons over one polygon using a loop in r. I have read that you need to use print in order to succesively display the polygons over the original polygon. However, that is not what R seems to do. Besides, in a hardly reproducible example, what i find is that either using print or not, the polygons will not plot within the loop. I am using a mac with OS monterrey, btw.
Here is a reproducible example, using print gives a bunch of NULL messages, but does print, not using print still plots. Yet a more complicated example will never plot from within the loop despite plotting everything when i request line by line from within the loop.
require(maptools)
data(wrld_simpl)
plot(wrld_simpl)
for (i in 1:12){
region=wrld_simpl[wrld_simpl$NAME==wrld_simpl$NAME[i],]
print(plot(region,border="red",add=T))
}
Maybe you're confusing print and plot? The plot function creates (or adds elements to) a plot. Whereas print function prints its arguments to the console. Since plot doesn't return a value, print has nothing to print and hence prints NULL.
Btw. you don't even need a loop. Since the loaded data wrld_simpl is of class SpatialPolygonsDataFrame, the object is subsettable like a dataframe you can just plot the needed indices:
plot(wrld_simpl)
plot(wrld_simpl[1:12,], border="red", add=T)
If you need help on a more complicated example, I suggest you share it?

How to store two plot in the same variable? [duplicate]

In ggplot2, one can easily save a graphic into a R object.
p = ggplot(...) + geom_point() # does not display the graph
p # displays the graph
The standard function plot produces the graphic as a void function and returns NULL.
p = plot(1:10) # displays the graph
p # NULL
Is it possible to save a graphic created by plot in an object?
base graphics draw directly on a device.
You could use
1- recordPlot
2- the recently introduced gridGraphics package, to convert base graphics to their grid equivalent
Here's a minimal example,
plot(1:10)
p <- recordPlot()
plot.new() ## clean up device
p # redraw
## grab the scene as a grid object
library(gridGraphics)
library(grid)
grid.echo()
a <- grid.grab()
## draw it, changes optional
grid.newpage()
a <- editGrob(a, vp=viewport(width=unit(2,"in")), gp=gpar(fontsize=10))
grid.draw(a)
I am very late to this, but it was the first question which showed up when I searched for the question. So I'd like to add my solution for future viewers who come across the question.
I solved this by using a function instead of an object. For example, suppose we want to compare two beta distributions with different parameters. We can run:
z1<-rbeta(10000,5,5)
z2<-rbeta(10000,20,20)
plotit<-function(vector,alpha,beta){
plot(density(vector),xlim=c(0,1))
abline(v=alpha/(alpha+beta),lty="longdash")
}
And save the plots as functions rather than objects.
z.plot1<-function(){plotit(z1,5,5)}
z.plot2<-function(){plotit(z2,20,20)}
Next, we can call each plot as we want by simply calling the two plots as functions rather than objects.
z.plot1()
plots the first plot and
z.plot2()
plots the second.
Hope that helps someone who stumbles across this later!
You can use the active binding feature of the pryr package if you don't want to directly change the values of the object created.
library(pryr)
a %<a-% plot(1:10,1:10)
Each time you type a on the console the graph will be reprinted on the screen. The %<a-% operator will rerun the script every time (in case of one graph this is not a problem I think). So essentially every time you use a the code will be rerun resulting in your graph which of course you can manipulate (overlay another plot on top) or save using png for example. No value itself will be stored in a however. The value will still be NULL.
I don't know if the above is what you are looking for but it might be an acceptable solution.
library(ggplot2)
# if mygraph is a plot object
ggsave("myplot1.png",mygraph)
# if the plot is in a list (e.g. created by the Bibliometrics package)
ggsave("myplot1.png",mygraphs[[1]])

Make multiple plots with function call in loop in R

I'm trying to make multiple plots with the following code. (da.list is a list of xts objects, and chart_Series is a plotting function from the quantmod package.)
library(quantmod)
plotLoan = function(loanID){
chart_Series( da.list[[loanID]], name = paste0('Loan ID: ', loanID))
}
LoanIDs = sample(names(da.list),6)
for (LoanID in LoanIDs) plotLoan(LoanID)
I'm not getting any output. However, plotLoan(LoanIDs[1]) produces a plot as expected. Why won't this work in a loop?
Have you tried using the layout command? Not sure exactly what's going on but I expect it has something to do with not having enough room in the graphics device. You can try
layout(matrix(seq(6), nrow=3, ncol=2))
layout.show(6)
which will partition the graphics output and show where the next 6 plots will go. If you want to produce a different number of plots you will have to choose the dimensions based on your needs.

Plot to specific plot in multiple-plot window?

If I create a multi-plot window with par(mfrow=...), is it possible to send data to a specific plot (i.e. "the one in the lower left corner") or is the plotting always necessarily sequential? Is there a package for R that does something like this?
For those that are interested, this problem arises out of the fact that R is a single-threaded application and is not ideal for real-time visualization. I have multiple real-time data streams coming into R from an outside source that produces the data asynchronously (and therefore the data streams don't always come in the same order). This results in R flipping around the order of the data visualization plots every time it updates.
You could use split.screen():
par(bg = "white") # erase.screen() will appear not to work
# if the background color is transparent
# (as it is by default on most devices).
split.screen(c(2,1)) # split display into two screens
split.screen(c(1,3), screen = 2) # now split the bottom half into 3
screen(1) # prepare screen 1 for output
plot(10:1)
screen(4) # prepare screen 4 for output
plot(10:1)
Have a look at help(layout). This allows you to specify the what, where and in which sizes.
Once plotted, I don't think you re-plot just partially. But you you can use dev.set() et al to switch between different 'plot devices' (ie windows); see help(dev.list).
Note that the suggested answer here is to use split.screen(). It may work, but according to the split.screen help file: "The recommended way to use these functions is to completely draw a plot and all additions (i.e. points and lines) to the base plot, prior to selecting and plotting on another screen. The behavior associated with returning to a screen to add to an existing plot is unpredictable and may result in problems that are not readily visible."
In an answer to my question, there is a more useful solution, using the par(mfg) option:
Change plot panel in multipanel plot in R
Another option is that of implementing a little GUI e.g. with RGtk2 or RTclTk.
I generally do this for graphs that I want to change in realtime and it works great.
For instance, with RGtk2 and cairoDevice you could just do something like (I assume you have a Glade interface)
# Helper function to get a widget from the Glade interface
getWidget <- function(name)
{
return (interface$getWidget(name))
}
interface <- gladeXMLNew("interface.glade", root="mainWindow")
# Our cairo devices (to draw graphics).
# plot1, plot2, and plot3 are GtkDrawingArea widgets
asCairoDevice(getWidget("plot1"))
# dev.cur() will give the device number of the last device we created
# You'll use this to switch device when you draw in different plots
# Storing the device number is important because you may have other
# devices open from other unrelated plots
# (so never assume they'll just start from 1 and be sequential!!!)
plot1.dev <- as.integer(dev.cur())
asCairoDevice(getWidget("plot2"))
plot2.dev <- as.integer(dev.cur())
asCairoDevice(getWidget("plot3"))
plot3.dev <- as.integer(dev.cur())
# To draw in a specific plot you just do
dev.set(plot2.dev)
plot(....)
This has many other advantages, like that of being able to positions the graphs easily where you want (using Glade Interface Designer) and having the possibility of user interaction through specific buttons (e.g. you may have a "pause acquisition" button).

Resources