Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 facet labeller with bquote

Tags:

r

ggplot2

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."

like image 213
user2165907 Avatar asked Oct 28 '25 06:10

user2165907


1 Answers

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)

like image 75
Jake Kaupp Avatar answered Oct 29 '25 19:10

Jake Kaupp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!