对facet_grid的特定行中的系数进行排序

cl25kdpy  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(153)

我使用facet_grid()来显示种族组和计划参与级别的模型类型的不同组合的2x2。
通过使用scales = "free",我可以将每行的y轴分离出来,只显示相关系数。但是,我如何指定每个面板行中的模型/变量顺序呢?通常,我会这样做:

model_order <- c("White", "Black", "Hispanic")

然后将其传递到scale_x_discrete()。(按顺序依次为高、中、低)。
但在这种情况下似乎不起作用,因为使用了scales = "free"。是否有控制顺序的变通方法?
编码:

mylabels <- c("1" = "Linear",
                       "2" = "Logit",
                       "3" = "Race",
                       "4" = "Level")

ggplot(dx, aes(x = var, y = coef,
       ymin = ci_lower, ymax = ci_upper)) +
  geom_point(size = 2) +
  geom_errorbar(width = 0.1,
                size = 1) +
  facet_grid(effect~model,
             scales = "free",
             labeller = as_labeller(mylabels)) + 
  scale_y_continuous(breaks = seq(-3, 3, by = 1)) +
  coord_flip() +
  theme_bw(base_size = 15) +
  theme(legend.position = "none")

数据来源:

structure(list(var = c("White", "Black", "Hispanic", "White", 
"Black", "Hispanic", "High", "Medium", "Low", "High", "Medium", 
"Low"), coef = c(1.64, 1.2, 0.4, 1.45, 0.17, 0.6, 1.04, 0.05, 
-0.74, -0.99, -0.45, -0.3045), ci_lower = c(1.3, 0.86, 0.06, 
1.11, -0.17, 0.26, 0.7, -0.29, -1.08, -1.33, -0.79, -0.6445), 
    ci_upper = c(1.98, 1.54, 0.74, 1.79, 0.51, 0.94, 1.38, 0.39, 
    -0.4, -0.65, -0.11, 0.0355), model = c(1, 1, 1, 2, 2, 2, 
    1, 1, 1, 2, 2, 2), effect = c(3, 3, 3, 3, 3, 3, 4, 4, 4, 
    4, 4, 4)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -12L), 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")), model = structure(list(), class = c("collector_double", 
    "collector")), effect = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), skip = 1L), class = "col_spec"))
mxg2im7a

mxg2im7a1#

您可以将变量定义为因子,然后重新排序它们的水平:

library(dplyr)
library(ggplot2)

mylabels <- c("1" = "Linear",
              "2" = "Logit",
              "3" = "Race",
              "4" = "Level")
dx %>% 
  mutate(var = forcats::fct_relevel(var,"High","Medium")) %>%
  ggplot(aes(x = var, y = coef,
                 ymin = ci_lower, ymax = ci_upper)) +
  geom_point(size = 2) +
  geom_errorbar(width = 0.1,
                size = 1) +
  facet_grid(effect~model,
             scales = "free",
             labeller = as_labeller(mylabels)) + 
  scale_y_continuous(breaks = seq(-3, 3, by = 1)) +
  coord_flip() +
  theme_bw(base_size = 15) +
  theme(legend.position = "none")

相关问题