我正在创建一个使用绘图函数的简单绘图,该绘图函数调用另一个绘图函数以通过它添加平滑线。第二个函数是lines()
并采用一些标准的基本图形参数。第一个函数也使用相同的命名参数。现在我想改变第二个图的一些元素而不改变第一个。我至少有几个我能想到的选择:
我开始思考是否可以在不重写任何内容的情况下将参数值传递给嵌套函数。请注意这个问题我不是要求一个函数来进行绘图 - 我可以编写自己的必要条件,我问我是否有可能在参数列表中指定traceplot
一个只会出现的参数如果它也是traceplot的命名参数,则传递给lines
。例如:
require(coda)
require(geoRglm)
# Some example data
mcmc <- c(0, 0, 0, 0, 0.5, 0.5, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0.5,
0.5, 1, 0.5, 0, 0.5, 0.5, 0.5, 0.5, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0.5, 0.5, 0, 0.5, 1, 0, 0.5, 1, 0.5, 0.5, 0.5, 0, 0.5, 0.5,
0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0.5, 0, 0, 0,
0.5, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0.5, 1, 1, 0, 1, 0,
0, 0.5, 0, 0.5, 0.5, 0, 0, 0, 0, 0, 0, 0.5, 0.5, 0.5, 0, 1, 0.5,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5,
1.5, 1, 1.5, 1, 1, 1, 1, 0.5, 0.5, 1, 1, 1.5, 1.5, 1.5, 1, 1.5,
1.5, 1.5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.5, 1, 1.5, 1.5,
1, 1.5, 1.5, 1, 1, 1, 1, 1)
# Input parameters for mcmc object
input <- structure(list(S.scale = 3.75e-05, Htrunc = "default", S.start = "default",
burn.in = 0, thin = 100, n.iter = 20000, phi.start = 0, phi.scale = 1), .Names = c("S.scale",
"Htrunc", "S.start", "burn.in", "thin", "n.iter", "phi.start",
"phi.scale"), class = "mcmc.geoRglm")
# create mcmc object
mcmc_obj <- create.mcmc.coda( mcmc , mcmc.input = input )
#Plot - smooth = TRUE draws the smooth line through the data
traceplot( mcmc_obj , smooth = TRUE , main = "Default")
# Changing the colour argument passes the same argument through to the lines function called to plot the smooth line
traceplot( mcmc_obj , smooth = TRUE , col = 2 , main = "Change colour to red")
# In the source code of traceplot 'lines()' is called to plot the smooth line.
# Can I specify a colour argument to be passed only to lines without altering
# the function?
# Excerpt from the source code of traceplot:
function (x, smooth = FALSE, col = 1:6, type = "l", ylab = "",
...)
{
... some code here then...
if (smooth) {
for (k in 1:nchain(x)) lines(lowess(xp, yp[, k])
}
}
答案 0 :(得分:1)
您可以使用两个列表传递不同的参数:
myfun <- function(x,y,par1=NULL,par2=NULL){
if(is.null(par1)){
plot(x,y)
}else{
do.call(plot,c(list(x=x,y=y),par1))
}
if(is.null(par2)){
lines(x,y)
}else{
do.call(lines,c(list(x=x,y=y),par2))
}
}
par1
表示plot
和par2
的参数,lines
的参数。如果您有这样的参数,请使用do.call
:
myfun(1:10,1:10) # no params
myfun(1:10,1:10,par1=list(pch=20)) # params only to plot
myfun(1:10,1:10,par1=list(pch=20),par2=list(col="red",lwd=2)) # params to plot and lines