首页 > 解决方案 > 在具有置信区间上限和下限时绘制 ggplot()

问题描述

请多多包涵,因为我对 R 很陌生,尤其是对 ggplot() 很陌生。这是我第二次询问有关使用此功能的问题。我想创建一个类似于下面的图:

在此处输入图像描述

我一直在使用一个看起来像这样的脚本来达到这个目的:


df <- tibble::tribble(~Proportion, ~Error, ~Time,
                      0.351 , 0.154, "Day",
                      0.223 , 0.157 , "Night")

dfnew <- df %>% 
  mutate(ymin = Proportion - Error,
         ymax = Proportion + Error)

p <-   ggplot(data = dfnew, aes(x = Time, y = Proportion)) +
  geom_point() + geom_line(aes(group = 1), color="lightblue",size=2) + 
  geom_errorbar(aes(x = Time, ymin = ymin, ymax = ymax),color="purple",width=0.1,size=1)


p<-p+theme(axis.text=element_text(size=12),
        axis.title=element_text(size=14))

但是,我现在面临的问题是,置信区间的数据包括上限和下限,而不是上面脚本中的错误值。我的数据如下所示:

> df
# A tibble: 2 x 4
  Average Lower Upper Time 
    <dbl> <dbl> <dbl> <chr>
1   0.351 0.284 0.421 Day  
2   0.223 0.178 0.275 Night

关于如何将这两个LowerUpper值实现到错误栏中的任何想法?

任何输入表示赞赏!

标签: rggplot2

解决方案


这有帮助吗?

使用新数据:

df2 <- read.table(
  header = T,
  stringsAsFactors = F,
  text = "  Average Lower Upper Time
1   0.351 0.284 0.421 Day  
2   0.223 0.178 0.275 Night"
)

并稍微调整绘图数据源:

ggplot(data = df2, aes(x = Time, y = Average)) +
  geom_point() +
  geom_line(aes(group = 1), color="lightblue",size=2) + 
  geom_errorbar(aes(x = Time, ymin = Lower, ymax = Upper),
                color="purple",width=0.1,size=1)

我得到这张图:

在此处输入图像描述

这看起来对我的眼睛来说是正确的,但我可能会遗漏一些你知道的东西。让我知道..


推荐阅读