在 R 中使用 tidyverse 和 pivot_longer 后如何使用 geom_errorbar?

How to use geom_errorbar after using tidyverse and pivot_longer in R?

我正在尝试使用 tidyversepivot_longer 稍后在 geom_errorbar 上绘制误差线(一个虚线和一个实线),但我相信我没有构建长格式正确或不知何故 error_bars 与功能没有很好的联系。

data<- data.frame(
          Date=(1:12),
          A=c(0,0,0,28.0,20.6,15.8,38.9,9.5,16.2,20.6,22.6,15.1),
          B= c(0,0,0,9.1,6.0,4.76,12.7,4.3,5.7,8.0,9.01,6.5),
          A_sd= c(0,0,0,6.3,11.4,1.49,6.96,1.23,1.4,1.15,6.3,1.2),
          B_sd=c(0,0,0,1.90,3.1,0.24,1.8,1.16,0.4,1.4,2.4,0.5))




LINETYPE1 <- c("A" = "solid", "B" = "dashed")
library(tidyverse)
data %>%
  select(A, B, A_sd, B_sd, Date) %>%
  pivot_longer(cols = -Date, -A_sd, -B_sd) %>%
  ggplot(aes(Date, value, linetype = name))  + 
  geom_line() +
  geom_point() + 
  scale_y_continuous(sec.axis = sec_axis(~./10, name= expression(paste("B", " (units)"))))+
  scale_linetype_manual(name= "", values= LINETYPE1, labels=c(bquote(A  ~ (pg ~cell ^-1)), bquote(B  ~ (units)))) +
  scale_x_datetime(labels = date_format("%b"))+
theme_classic()+
  ylab(bquote(A  ~ (units)))+
  geom_errorbar(aes(ymin = A, ymax = A +A_sd), 
                position = position_dodge2(padding = 0.6, width = 0.5))+
  geom_errorbar(aes(ymin = B, ymax = B+B_sd), 
                position = position_dodge2(padding = 0.6, width = 0.5))+
  xlab("")

现在给出错误:

Error in build_longer_spec(data, !!cols, names_to = names_to, values_to = values_to, : object 'B_sd' not found

我很想得到这样的东西

是的,您的支点不太正确。从示例数据中执行此操作的最简单方法是首先将 AB 重命名为 A_meanB_mean,然后在中使用 names_sep 方法pivot_longer。这样,您可以调用:

pivot_longer(-Date, names_sep = "_", names_to = c("group", ".value")) 

为日期、组 (A/B)、均值和标准差各留一列。

完整的代码是这样的:

data %>%
  select(A, B, A_sd, B_sd, Date) %>%
  rename(A_mean = A, B_mean = B) %>%
  pivot_longer(-Date, names_sep = "_", names_to = c("group", ".value")) %>%
  ggplot(aes(Date, mean, linetype = group)) + 
  geom_line() +
  geom_point() + 
  scale_y_continuous(sec.axis = sec_axis(~./10, 
                        name= expression(paste("B", " (units)")))) +
  scale_linetype_manual(name= "", values = LINETYPE1, 
                        labels=c(bquote(A  ~ (pg ~cell ^-1)), 
                                 bquote(B  ~ (units)))) +
  scale_x_datetime(labels = scales::date_format("%b")) +
  theme_classic(base_size = 16) +
  ylab(bquote(A  ~ (units)))+
  geom_errorbar(aes(ymin = mean -sd, ymax = mean + sd), alpha = 0.5) +
  xlab("")

请注意,我必须稍微修改您的输入数据以将 Date 列更改为实际日期,否则您的 scale_x_datetime 调用将不起作用。