4

Yet another labeller question... I am struggling using math expressions in labellers with ggplot2 > 3

library(ggplot2)

var.lab1 = as_labeller(c(
  "setosa" = "se", 
  "versicolor" = "ve", 
  "virginica" = "vi"
))

var.lab2 = as_labeller(c(
  "setosa" = bquote("Spp"[set]), 
  "versicolor" = bquote("Spp"[ver]), 
  "virginica" = bquote("Spp"[vir])
))

This works as expected

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
  facet_wrap(~ Species, labeller = var.lab1) +
  geom_point()

This doesn't work (the labeller has no effect)

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
  facet_wrap(~ Species, labeller = var.lab2) +
  geom_point()

And this works

var.lab3 = c(
  "setosa" = bquote("Spp"[set]), 
  "versicolor" = bquote("Spp"[ver]), 
  "virginica" = bquote("Spp"[vir])
)

vlabeller <- function (variable, value) {
  return(var.lab3[value])
}

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
  facet_wrap(~ Species, labeller = vlabeller) +
  geom_point()

But ggplot2 is unhappy "Warning message: The labeller API has been updated. Labellers taking variable and value arguments are now deprecated. See labellers documentation."

user2165907
  • 1,401
  • 3
  • 13
  • 28

1 Answers1

2

You could just use label_bquote and substr to get what you want. No need for a custom labeller.

library(ggplot2)

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
  facet_wrap(~ Species, labeller = label_bquote(cols = "Spp"[.(substr(Species, 1, 3))])) +
  geom_point()

Created on 2018-11-22 by the reprex package (v0.2.1)

Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36
  • 4
    Yes, your answer is correct for my particular (and simple) example, that's why I have to validate it. Unfortunately, I am working on a bigger (many more facets) "true life" dataset and each facet has a different kind of labeller, some with bquote and others without... So, if there are other propositions I'll be happy. – user2165907 Nov 22 '18 at 17:54