[英]Create a ggplot2 geom for a line and confidence interval
I would like to design a geom to plot a line with a confidence interval around it.我想设计一个几何图形来绘制一条带有置信区间的线。 The data frame that this will be based on contains the following:这将基于的数据框包含以下内容:
For example,例如,
xvals <- seq(0,2*pi,length=100)
df <- data.frame(x=xvals, y=sin(xvals), se=.25)
head(df)
x y se
1 0.00 0.000000000 0.25
2 0.01 0.009999833 0.25
3 0.02 0.019998667 0.25
4 0.03 0.029995500 0.25
5 0.04 0.039989334 0.25
6 0.05 0.049979169 0.25
I followed the guidelines laid out here to write the following geom function:我按照此处列出的指南编写了以下 geom 函数:
geom_myci <- function(yvar, sevar) {
list(geom_ribbon(mapping=aes_q(ymin=substitute(yvar-1.96*sevar),
ymax=substitute(yvar+1.96*sevar)),
colour="lightgrey", fill="lightgrey"),
geom_line(mapping=aes_q(y=substitute(yvar)), lwd=2),
theme_bw())
}
This can be then executed using:然后可以使用以下方法执行:
ggplot(df, aes(x,y)) + geom_myci(y,se)
This works great, the only thing I don't like is I make the user enter the y variable twice.这很好用,我唯一不喜欢的是我让用户输入 y 变量两次。 Is there any way, within the geom
function, to know the variable that is already mapped to "y"?在geom
函数中,有没有办法知道已经映射到“y”的变量?
You can do this via aes_string
with substitute
of the se -Variable as follows - Have a look at http://adv-r.had.co.nz/Functions.html to see how substitute
and lazy evaluation works您可以通过aes_string
substitute
se -Variable,如下所示 - 查看http://adv-r.had.co.nz/Functions.html以了解substitute
和延迟评估的工作原理
geom_myci <- function(se_var = se) {
se_var <- as.character(substitute(se_var))
list(geom_ribbon(aes_string(ymin = sprintf("y - 1.96 * %s", se_var),
ymax = sprintf("y + 1.96 * %s", se_var)),
colour="lightgrey", fill="lightgrey"),
geom_line(lwd=2),
theme_bw())
}
as.character(substitute(se_var))
makes se_var
a sting. as.character(substitute(se_var))
使se_var
成为刺痛。 In this example "se"
.在这个例子中"se"
。 Now you can use this to build the aes_string via sprintf("y - 1.96 * %s", se_var)
which results in现在您可以使用它通过sprintf("y - 1.96 * %s", se_var)
,结果是"y - 1.96 * se"
- the string we need. "y - 1.96 * se"
- 我们需要的字符串。
Plotting it results (as asked for) in绘制它的结果(按要求)在
ggplot(df, aes(x,y)) + geom_myci()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.