【问题标题】:R pivot_longer and ggplot errorbar with two name/key columnsR pivot_longer 和 ggplot 带有两个名称/键列的误差线
【发布时间】:2020-05-06 12:46:04
【问题描述】:

假设我们有以下人工数据:

  df <- data.frame(Year = c(2015,2016,2017,2018),
               GPP_mean = c(1700,1800,1750,1850),
               Reco_mean = c(-1700,-1800,-1750,-1850),
               GPP_min = c(1600,1700,1650,1750),
               GPP_max = c(1800,1900,1850,1950),
               Reco_min = c(-1600,-1700,-1650,-1750),
               Reco_max = c(-1800,-1900,-1850,-1950))

我想为每个平均值绘制条形图,并使用最小/最大列作为误差线。 这是我到目前为止所取得的成就:

df %>%
    pivot_longer(cols = -Year,
                 names_to = c("variable", "stats"),
                 names_sep = "_") 

这给了我们:

    # A tibble: 24 x 4
    Year variable stats value
   <dbl> <chr>    <chr> <dbl>
 1  2015 GPP      mean   1700
 2  2015 Reco     mean  -1700
 3  2015 GPP      min    1600
 4  2015 GPP      max    1800
 5  2015 Reco     min   -1600
 6  2015 Reco     max   -1800
 7  2016 GPP      mean   1800
 8  2016 Reco     mean  -1800
 9  2016 GPP      min    1700
10  2016 GPP      max    1900
# … with 14 more rows

到目前为止,一切都很好(我猜?)。 从这里开始,我不知道如何告诉 ggplot 将平均值绘制为条形图并使用最小/最大值作为误差线。任何帮助表示赞赏,谢谢。

【问题讨论】:

    标签: r ggplot2 tidyr errorbar


    【解决方案1】:

    使用tidyverse的其他解决方案

    library(tidyverse)
    out <- df %>% 
      pivot_longer(-Year, names_sep = "_", names_to = c("index", ".value"))
    
    ggplot(out, aes(Year, mean, fill = index)) +
      geom_col() +
      geom_errorbar(aes(ymin = min, ymax = max), width = 0.5)
    

    【讨论】:

      【解决方案2】:

      您应该坚持使用原始数据框。无需为此花费更长的时间:

        ggplot(df, aes(Year, GPP_mean)) + 
          geom_col(fill = "forestgreen", colour = "black") + 
          geom_errorbar(aes(ymin = GPP_min, ymax = GPP_max), width = 0.5) +
          geom_col(aes(y = Reco_mean), fill = "red", colour = "black", position = "dodge") + 
          geom_errorbar(aes(ymin = Reco_max, ymax = Reco_min), width = 0.5)
      

      【讨论】:

      • 我有一段时间避免收集/pivot_longer,现在我正努力适应它,因为我认为这就是 tidyverse 的用途。但似乎在某些情况下,“整洁”的 data.frame 弊大于利。我仍然想知道是否可以按照我处理数据的方式绘制数据,但无论如何感谢您的回答。
      • @FelixPhl 我仍然会将其视为整洁的数据。每个观测值有 6 个变量,以及 4 个唯一观测值(年)。旋转更长的时间是一个强大的工具,我经常使用它,但工具的存在只是为了帮助我们实现最终产品。如果您发现自己使用特定工具只是因为“这是您应该做的”,而这样做对您或其他任何人绝对没有好处,那么您正在进入Cargo cult programming
      猜你喜欢
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 2013-01-10
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2022-09-26
      相关资源
      最近更新 更多