HLee
HLee

Reputation: 23

use multiple options for multiple plots

I'd like to plot two (or more) graphs that have the same plot-options. The code will look like

plot(data1, type='l', lwd=2, col=c(1,1,2,1,3,1), pch=19)
plot(data2, type='b', lwd=2, col=c(1,1,2,1,3,1), pch=19)

It would be nice if I can keep some options in variables. The code will look like

my_opt <- list(lwd=2, col=c(1,1,2,1,3,1), pch=19)
plot(data1, type='l', my_opt)   ## it does not work
plot(data2, type='b', my_opt)

Is there a way to make it work?

Upvotes: 2

Views: 53

Answers (2)

PKumar
PKumar

Reputation: 11128

I believe you are looking for do.call, with do.call you can do a lot of things, one of them to pass the arguments in the form of list.

data1 <- data.frame(x = 1:10, y = (1:10)**2)
data2  <- data.frame(x = seq(1,10,2), y = 1:5)

my_opt <- list(lwd=2, col=c(1,1,2,1,3,1), pch=19)
do.call(plot, c(data1, type ="l", my_opt) )  
do.call(plot, c(data2, type ="b", my_opt) )  

enter image description here

Upvotes: 2

Conor Neilson
Conor Neilson

Reputation: 1091

You could write a small wrapper function instead

myplot <- function(mydata, ...){
 plot(mydata, lwd = 2, col = c(1,1,2,1,3,1), pch = 19, ...)
}

myplot(data1, type = "l")
myplot(data2, type = "b")

Upvotes: 2

Related Questions