Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bquote does not work in facet_grid labels in ggplot2 version 2.1

Tags:

r

ggplot2

I have the following code that worked perfectly in some old pre-2.1 version of ggplot2:

dd <-
structure(list(Dataset = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("train", 
"validation"), class = "factor"), Iterations = c(4L, 2L, 3L, 
4L, 1L, 3L), L1 = c(1e-07, 1e-07, 1e-07, 1e-06, 1e-07, 1e-06), 
    L2 = c(1e-05, 1e-05, 1e-05, 1e-05, 1e-05, 1e-05), Accuracy = c(0.2079478, 
    0.2079829, 0.2081201, 0.2086698, 0.2091378, 0.2093453), Loss = c(0.4468469, 
    0.446877, 0.4472973, 0.4485992, 0.4496757, 0.4499354)), .Names = c("Dataset", 
"Iterations", "L1", "L2", "Accuracy", "Loss"), row.names = c(NA, 
6L), class = "data.frame")

labelAxis <- function(i) {
  function(values) {
    sapply(values, function(x) { bquote(lambda[.(i)]==10^.(round(log10(x)))) })
  }
}

ggplot(dd, aes(x=Iterations, y=Loss, color=Dataset)) +
  facet_grid(. ~ L1 + L2, scales="fixed",
             labeller=labeller(L1=labelAxis(1), L2=labelAxis(2), keep.as.numeric=T)) +
  geom_line()

Now ggplot2 deprecates the labeller() keep.as.numeric=... parameter, and, worse yet, for the code above it no longer produces nice math rendering of the labels. Does anyone know how to fix that issue?

like image 766
Sergiy Matusevych Avatar asked Jun 16 '16 00:06

Sergiy Matusevych


1 Answers

Ok, I think I've figured it out. The new way to edit facet labels is to use label_bquote(), like this:

ggplot(dd, aes(x=Iterations, y=Loss, color=Dataset)) +
  facet_grid(. ~ L1 + L2, scales="fixed", labeller=label_bquote(
    cols={lambda[1]==10^.(round(log10(L1)))}*", "*lambda[2]==10^.(round(log10(L2))))) +
  geom_line()

Note that seemingly random pair of curly braces. That's an R gotcha. Without those braces R parser chokes on a second == operator in the expression.

like image 138
Sergiy Matusevych Avatar answered Nov 08 '22 02:11

Sergiy Matusevych