如何写一个函数来创建用于ggplot2的自定义错误栏? [英] How can one write a function to create custom error bars for use with ggplot2?

查看:85
本文介绍了如何写一个函数来创建用于ggplot2的自定义错误栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ggplot2允许将一个错误条添加到一个图中。要为您计算误差线限制,它会包含来自Hmisc的函数。例如,引导程序可以使用mean_cl_boot选项:

Ggplot2 allows one to add error bars to a plot. To calculate the error bar limits for you, it wraps functions from Hmisc. For example, to bootstrap one can use the mean_cl_boot option:

m <- ggplot(mtcars, aes(x=cyl, y=am)) + stat_summary(fun.y=mean,geom="point")
m2 <- m + stat_summary(fun.data = "mean_cl_boot", geom = "errorbar", conf.int=.95)
m2

但是如果您需要编写自定义函数来计算错误栏限制?应该如何编写函数以便从stat_summary调用中调用?

But what if you need to write a custom function to calculate the error bar limits? How should the function be written to be invoked from a stat_summary call?

推荐答案

以下是使用PropCI提供的add4ci函数的示例置信区间。您只需要让该函数返回一个名为y,ymin和ymax的数字列表:

Here's an example using the add4ci function from PropCIs providing a confidence interval. You just need to have the function return a list of numbers named "y", "ymin", and "ymax":

library(PropCIs)
add4ciForGgplot <- function(x,conf.int) {
numCorrect <- sum(x)
numTrials <- length(x)
CI <- add4ci(numCorrect,numTrials,conf.int)
triplet <- data.frame(numCorrect/numTrials, CI$conf.int[1], CI$conf.int[2])
names(triplet) <- c("y","ymin","ymax") #this is what ggplot is expecting
return (triplet)
}

m <- ggplot(mtcars, aes(x=cyl, y=am)) + stat_summary(fun.y=mean,geom="point")
mCustom <- m + stat_summary(fun.data = "add4ciForGgplot", geom = "errorbar", conf.int=.95)
mCustom

这篇关于如何写一个函数来创建用于ggplot2的自定义错误栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆