R pivot_longer 和带有两个 name/key 列的 ggplot errorbar

R pivot_longer and ggplot errorbar with two name/key columns

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

  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))

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

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 将平均值绘制为条形图并使用 min/max 作为误差条。感谢任何帮助,谢谢。

您应该坚持使用原始数据框。没有必要为此转动更长的时间:

  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)

使用 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)