【问题标题】:How to create a diurnal plot that includes standard deviation bars (Reproducible example)如何创建包含标准偏差条的昼夜图(可重现的示例)
【发布时间】:2022-01-20 21:11:27
【问题描述】:

我在两个月内以每小时的时间间隔有一组数据(df 作为示例子集提供)。

我希望能够在 24 小时内创建一个昼夜图,并且还包括“误差”条,即 24 小时内每个相应小时的标准偏差(类似于下面提供的片段)

如果有人知道如何做到这一点,我将不胜感激。

可重现的例子:

df <- structure(list(date = structure(c(1623394800, 1623398400, 1623402000, 
1623405600, 1623409200, 1623412800, 1623416400, 1623420000, 1623423600, 
1623427200, 1623430800, 1623434400, 1623438000, 1623441600, 1623445200, 
1623448800, 1623452400, 1623542400, 1623546000, 1623549600, 1623553200, 
1623556800, 1623560400, 1623564000, 1623481200, 1623484800, 1623488400, 
1623492000, 1623495600, 1623499200, 1623502800, 1623506400, 1623510000, 
1623513600, 1623517200, 1623520800, 1623524400, 1623528000, 1623531600, 
1623535200, 1623538800), tzone = "", class = c("POSIXct", "POSIXt"
)), Normalized = c(0.0791523227961842, 0.0387684846348657, 0.0169612120277537, 
0, 0.00861521880774794, 0.0498067337322928, 0.237995419564037, 
0.43372242185256, 0.571296697188785, 0.57452740424169, 0.586642555690086, 
0.660410366731428, 0.78883097208442, 0.713717033104368, 0.718293868095984, 
0.764331443599887, 0.716140063394047, 1, 0.886130921162445, 0.709001242970692, 
0.648271067590662, 0.554223643217422, 0.402398204767348, 0.272924844755757, 
0.243403231723798, 0.132908051518466, 0.0257867699453584, 0.00723032746812717, 
0.010604226100351, 0.0662735535320448, 0.140921060769998, 0.253946664949497, 
0.29105954990396, 0.38299828763206, 0.568984449733401, 0.679901367267761, 
0.691288275151516, 0.670623146029145, 0.686649164532208, 0.672310095345257, 
0.814435575227687)), row.names = c(NA, -41L), class = c("tbl_df", 
"tbl", "data.frame"))

【问题讨论】:

    标签: r dataframe plot time graph


    【解决方案1】:

    这是一个使用 ggplot2 和 dplyr 的解决方案:

    library(ggplot2); library(dplyr)
    

    首先您必须定义您的误差线,我刚刚使用每小时的标准偏差作为代表性误差线长度。如果您想使用不同的组作为标准差,您只需更改 group_by 中的条目即可:

    df <- df %>% mutate( day = format(date, "%d"),
                   hour = format(date, "%H")) %>% 
      group_by(day) %>% 
      summarize(errorbar = sd(Normalized),
                date=date, day=day) %>% 
      left_join(df, ., by="date")
    

    然后我使用函数geom_errorbar 来创建错误栏:

    ggplot(df, aes(x=date, y=Normalized)) +
      geom_line() +
      geom_point() +
      geom_errorbar(aes(ymin=Normalized-errorbar, ymax=Normalized+errorbar), width=.2,
                    position=position_dodge(.05)) +
      theme_bw()
    

    这给出了以下解决方案:

    如果您想使用不同的绘图,例如每天,您只需将+facet_wrap(.~day) 添加到情节即可实现此目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2019-11-14
      相关资源
      最近更新 更多