我有一个data.frame,其中包含表格的许多列,包含变量x,y,z,w的每个时间点的聚合值...: 时间x_mean x_sd y_mean y_sd z_mean y_sd w_mean w_sd ...
现在我想编写一个函数,用ggplot2绘制平均值和围绕它的+/- 1SD的置信带。目前我的代码如下:
plotfunc <- function(ds1,val) {
val_mean <- paste(val,"_mean",sep="")
val_p_sd <- paste(val,"_mean + ",val,"_sd",sep="")
val_m_sd <- paste(val,"_mean - ",val,"_sd",sep="")
ggplot() + geom_line(data=ds1,aes_q(x=as.name("TIME"),y=as.name(val_mean),color="good")) +
geom_ribbon(data=ds1,aes_q(x=as.name("TIME"),ymin=as.name(val_m_sd),ymax=as.name(val_p_sd),alpha=0.3,fill="good"))
}
我称之为:
plotfunc(df,"x")
它抱怨道:
Error in eval(expr, envir, enclos) : object 'x_mean - x_sd' not found
如何获得上限和下限?我需要使用substitute
或quote
吗?
答案 0 :(得分:1)
我使用aes_string
并更正了函数代码中的一些语法错误:
- 颜色“好”未知
- 因此,指定为固定值的颜色参数不在aes
函数
df = data.frame("TIME"=11:20, "x_mean"=rnorm(10, mean=10), "x_sd"=rnorm(10, mean=1, sd=0.1),
"y_mean"=rnorm(10, mean=12), "y_sd"=rnorm(10, mean=2, sd=0.2))
plotfunc <- function(ds1,val) {
val_mean <- paste(val,"_mean",sep="")
val_p_sd <- paste(val,"_mean + ",val,"_sd",sep="")
val_m_sd <- paste(val,"_mean - ",val,"_sd",sep="")
ggplot() + geom_line(data=ds1,aes_string(x=as.name("TIME"),y=as.name(val_mean)),color="red") +
geom_ribbon(data=ds1,aes_string(x=as.name("TIME"),ymin=as.name(val_m_sd),ymax=as.name(val_p_sd)),alpha=0.3,fill="blue")
}
plotfunc(df,"x")