R:如何按方差对误差图进行排序?

R: How do you order error plots by variance?

是否可以根据方差对 R 中的误差图进行排序?以便它们从最大方差到最小方差?

代码:

library(ggplot2)

df <- ToothGrowth
df$dose <- as.factor(df$dose)
head(df, 3)

library(dplyr)
df.summary <- df %>%
  group_by(dose) %>%
  summarise(
    sd = sd(len, na.rm = TRUE),
    len = mean(len)
  )
df.summary


f <- ggplot(
  df.summary, 
  aes(x = dose, y = len, ymin = len-sd, ymax = len+sd)
  )

f + geom_pointrange()

# Standard error bars
f + geom_errorbar(width = 0.2) +
  geom_point(size = 1.5)

如有任何帮助,我们将不胜感激!

继续管道将 sd 强制为有序因子,其顺序由数字 sd 给出。然后按照问题绘制。所有需要更改的是下面的 mutate

df.summary <- df %>%
  group_by(dose) %>%
  summarise(
    sd = sd(len, na.rm = TRUE),
    len = mean(len)
  ) %>%
  mutate(i = order(sd, decreasing = TRUE),
         dose = ordered(dose, levels = dose[i])) %>%
  select(-i)