R: re-label facet_wrap ggplot2 中的标题

R: re-label facet_wrap titles in ggplot2

library(ggplot2)
library(tidyverse)
dummy_data <- structure(list(csh = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("0", 
"1", "2", "3", "4"), class = "factor"), method = structure(c(4L, 
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("avg_ratio", "stack_learner_ratio", "stack_ratio", 
"y_bar_ratio"), class = "factor"), mse = c(1.71440060270582, 
2.3039074506099, 2.2045472757757, 1.44682474607404, 1.93635013676601, 
2.23555711509222, 1.14505211151131, 1.3985843445545, 1.86464256037161, 
1.26212385917695, 1.04872854298465, 1.30606672079847, 1.06559000879232, 
1.0111077548544, 1.14771201947952, 1.01244435100631, 0.971703540094071, 
1.06385665414544)), row.names = c(1L, 2L, 3L, 101L, 102L, 103L, 
201L, 202L, 203L, 501L, 502L, 503L, 601L, 602L, 603L, 701L, 702L, 
703L), class = "data.frame")

我正在尝试根据 csh 值重新标记 facet_wrap 标题。我正在使用以下代码,但它似乎没有执行我想要的操作?

dummy_data %>%
  ggplot(aes(x = method, y = mse, fill = method)) +
  geom_boxplot() +
  facet_wrap(~csh, labeller = labeller(csh = c("0" = expression(paste(beta[0])),
                                               "1" = expression(paste(beta[1])),
                                               "2" = expression(paste(beta[2]))))) +
  theme_bw() +
  theme(axis.text.x=element_blank())

试试这个方法。您可以使用所需的组合直接为标签创建一个变量,然后使用 label_parsed 对其进行评估。这里的代码:

library(ggplot2)
library(dplyr)
#Code
dummy_data %>%
  mutate(csh=paste('beta[',csh,']')) %>%
  ggplot(aes(x = method, y = mse, fill = method)) +
  geom_boxplot() +
  facet_wrap(~csh, labeller = label_parsed) +
  theme_bw() +
  theme(axis.text.x=element_blank())

输出:

更新:

#Code 2
dummy_data %>%
  mutate(csh=paste("beta==", csh)) %>%
  ggplot(aes(x = method, y = mse, fill = method)) +
  geom_boxplot() +
  facet_wrap(~csh,labeller = label_parsed) +
  theme_bw() +
  theme(axis.text.x=element_blank())

输出: