0
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")

I'm trying to relabel the facet_wrap titles depending on the csh value. I'm using the following code, but it does not seem to do what I want it to do?

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())

enter image description here

Adrian
  • 9,229
  • 24
  • 74
  • 132
  • you just need `dummy_data %>% ggplot(aes(x = method, y = mse, fill = method)) + geom_boxplot() + facet_wrap(~ csh, labeller = label_bquote(beta[.(csh)]))` – akrun Oct 19 '20 at 22:34

1 Answers1

0

Try this approach. You can directly create a variable for the label using the desired combination and then use label_parsed for its evaluation. Here the code:

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())

Output:

enter image description here

Update:

#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())

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • Thanks. One follow-up question. What if I wanted the label to be beta = 0, beta = 1, and beta = 2 instead? I tried `mutate(csh=paste('beta = ', csh))` but that did not give me what I wanted. – Adrian Oct 19 '20 at 22:13
  • @YQC Let me add an update for you in this moment! – Duck Oct 19 '20 at 22:14
  • 1
    @YQC I have added an update for you. I hope that helps you!!! – Duck Oct 19 '20 at 22:22