Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign barplot/plot to a variable and recall at later stage

Tags:

plot

r

How can I assign plot to a variable and have it printed it at later stage? With lattice xyplot you can do it easily:

s <- xyplot((1:10)^2~1:10)
s

However not with base plot

a <- plot((1:10)^2,1:10)

What I have got is a barplot in a function:

funbar <- function(x) { barplot(x) }
variab <- funbar(1:10) # this plots the data

So I would like it to print at later stage by calling variab

In fact I have additional graphical functions in a function, something like this:

funbar <- function(x) { barplot(x); points(....); text(....) }

I could not find any info on this obvious part. The plot=FALSE doesn't help here.

EDIT: Here are the data for barplot taken from ?barplot

require(grDevices) # for colours
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20))

EDIT 2: To answer Josh question as of why I would like to do this. Example:

layout(matrix(1:2, nrow=2, ncol=1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN)
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN)
like image 465
Maximilian Avatar asked Nov 26 '25 13:11

Maximilian


1 Answers

Perhaps this can be solved with xy.coords:

a <- xy.coords((1:10)^2,1:10) #plots nothing

And can be plotted later:

plot(a)

I came upon this idea by examining the code for plot.default.

As for barplots, perhaps the rect function will accomplish something similar (as this seems to be at core of what barplot.default is doing).

like image 158
MichaelChirico Avatar answered Nov 29 '25 18:11

MichaelChirico