简体   繁体   English

ggplot的置信区间误差线

[英]confidence interval error bars for ggplot

I want to put confidence interval error bars for ggplot.我想为 ggplot 放置置信区间误差线。

I have a dataset and I am plotting it with ggplot as:我有一个数据集,我用 ggplot 将其绘制为:

df <- data.frame(
        Sample=c("Sample1", "Sample2", "Sample3", "Sample4", "Sample5"), 
        Weight=c(10.5, NA, 4.9, 7.8, 6.9))

p <- ggplot(data=df, aes(x=Sample, y=Weight)) + 
geom_bar(stat="identity", fill="black") + 
scale_y_continuous(expand = c(0,0), limits = c(0, 8)) + 
theme_classic() + 
theme(axis.text.x = element_text(angle = 45, hjust = 1)

p

I am new to adding error bars.我是添加误差线的新手。 I looked at some options using geom_bar but I could not make it work.我使用 geom_bar 查看了一些选项,但无法使其工作。

I will appreciate any help to put confidence interval error bars in the barplot.我将不胜感激将置信区间误差线放入条形图中的任何帮助。 Thank you!谢谢!

Add a layer of error bars with geom_errorbar使用geom_errorbar添加一层误差线

df <- data.frame(
  Sample=c("Sample1", "Sample2", "Sample3", "Sample4", "Sample5"), 
  Average.Weight=c(10.5, NA, 4.9, 7.8, 6.9),
  # arbitrarily make up some Standard Errors for each mean:
  SE = c(1, NA, .3, .25, .2)) # JUST MAKING THINGS UP HERE

Now you have a data frame with a column of Average Weight and the SE for each sample in your study.现在,您有一个数据框,其中有一列Average Weight和研究中每个样本的SE Use ggplot to plot:使用ggplot到 plot:

ggplot(data = na.omit(df)) + #don't bother plotting the NA
  geom_bar(stat = "identity", aes(x = Sample,y = Average.Weight)) +
  geom_errorbar(
    aes(x=Sample, 
        ymin = Average.Weight - 2*SE, 
        ymax = Average.Weight + 2*SE), 
    color = "red"
  )

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM