按大小重新排列 geom_point

Rearrange geom_point by size

我有一个变量 (-coef-),它只是回归系数值。我希望根据各自的 -coef- 值的大小在我的图中安排所有 -var-(不同模型的变量)。我尝试过使用 reorder() 的各种解决方案(例如 https://www.rpubs.com/dvdunne/reorder_ggplot_barchart_axis),但它们似乎都针对 geom_bar 或 geom_col 并且没有使用 geom_point/geom_errorbar.

ggplot(d, aes(x = var, y = coef,
              ymin = ci_lower, ymax = ci_upper,
              color = var)) +
  geom_point(size = 2) +
  geom_errorbar(width = .5,
                size = 1) +
  coord_flip() +
  theme_minimal()

编辑:一些示例数据

d <- structure(list(var = c("a", "b", "c", "d", "e", "f", "g", "h", 
"i", "j"), coef = c(0.1, 0.2, 0.3, 0.35, 0.46, 0.64, 0.54, 0.13, 
0.87, 0.41), ci_lower = c(0.05, 0.15, 0.25, 0.3, 0.41, 0.59, 
0.49, 0.08, 0.82, 0.36), ci_upper = c(0.15, 0.25, 0.35, 0.4, 
0.51, 0.69, 0.59, 0.18, 0.92, 0.46)), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), spec = structure(list(
    cols = list(var = structure(list(), class = c("collector_character", 
    "collector")), coef = structure(list(), class = c("collector_double", 
    "collector")), ci_lower = structure(list(), class = c("collector_double", 
    "collector")), ci_upper = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1L), class = "col_spec"))

您可以通过“coef”arrange 您的数据,然后使用 factor(ordered = T) 重新编码“var”。请注意,ggplot 将为有序因子切换到不同的色标,因此我还在图中指定了 scale_color_hue()

d %>% 
  arrange(coef) %>% 
  mutate(var = factor(var, unique(var), ordered = T)) %>% 
ggplot(., aes(x = var, y = coef,
              ymin = ci_lower, ymax = ci_upper,
              color = var)) +
  geom_point(size = 2) +
  geom_errorbar(width = .5,
                size = 1) +
  scale_color_hue() +
  coord_flip() +
  theme_minimal()