给定数据的geom_bar和错误栏

时间:2015-08-08 15:19:41

标签: r ggplot2 bar-chart confidence-interval

我想为this data

设置小节和错误栏

我设法得到了酒吧:

ggplot(FCDreach_global_mod, aes(x = as.factor(t3-t2), y = 1-value, fill=as.factor(t2-t1) )) + 
  geom_bar(stat = "identity" )

但是我不知道如何绘制错误栏。我试过了geom_errorbar(),但无法让它发挥作用。

绘制线条图时,我会使用:

stat_summary(fun.data=mean_cl_normal, geom="errorbar")  

但这似乎与geom_bar()

无法正常工作

我试过了:

ggplot(FCDreach_global_mod, aes(x = as.factor(t3-t2), y = 1-value, fill=as.factor(t2-t1) ) ) + 
  stat_summary(fun.y=mean,geom="bar")+
  stat_summary(fun.data=mean_cl_normal,geom="errorbar", width=0.5) 

y相比,geom_bar(stat = "identity" )上的休息时间与x相比有所不同。条形的大小是相同的,但是y尺度会发生奇怪的事情。

geom_bar: enter image description here

stat_summary:

enter image description here

编辑:所需的输出是在条形图中显示该图的等效值,当然不包括t3-t2轴并将x放在ggplot(FCDreach_global_mod, aes(x=roundedRealNumVehicles/2, y=1-value, colour=as.factor(t3-t2), lty=as.factor(t2-t1)) ) + stat_summary( fun.y=mean, geom="line" ) + stat_summary(fun.data=mean_cl_normal,geom="errorbar", width=0.5)

enter image description here

我通过以下方式获得:

<script language="javascript" type="text/javascript">
function addshortcode() {
    var shortcode = "[myshortcode]";
    document.myform.editor.value += shortcode;
}
</script>

<form name="myform">
<input type="button" value="Add Shortcode" onClick="addshortcode();"><br />
<textarea name="editor"></textarea>
</form>

1 个答案:

答案 0 :(得分:2)

在第一张图中,y轴表示(t3-t2)每个等级的(1值)总和。在第二个中,y轴是平均值。因此,您可以手动使用aggregate重新创建这些值,

## Question 1: what is the y-axis of the first plot?
## Aggregate by summing (1-value)
(p1 <- aggregate((1-value) ~ I(t3-t2), data=FCDreach_global_mod, sum))
#   I(t3 - t2) (1 - value)
# 1        0.4    19.51663
# 2        0.5    19.70297

## Question 2: where does the 0.075 come from in the stat_summary?
## Aggregate (1-value) taking the mean
(p2 <- aggregate((1-value) ~ I(t3-t2), data=FCDreach_global_mod, mean))
#   I(t3 - t2) (1 - value)
# 1        0.4  0.09119921
# 2        0.5  0.09038062

## Get normal confidence intervals
se <- with(FCDreach_global_mod,
           do.call(rbind,
                   lapply(split(1 - value, factor(t3-t2)), function(x)
                       mean(x) + c(-1,1)*sd(x)/sqrt(length(x))*qnorm(0.975))
                   ))


## Recreate barplot
dat <- setNames(p2, c("x", "y"))
dat <- cbind(dat, setNames(data.frame(se), c("ymin", "ymax")))

ggplot(dat, aes(x,y)) +
  geom_bar(stat="identity", aes(fill=factor(x))) +
  geom_errorbar(aes(x=x, ymin=ymin, ymax=ymax), color="black", width=0.05) +
  theme_bw()

enter image description here