Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom label to facet_grid()

Tags:

r

ggplot2

I'm trying to add a a custom facet label to a plot that was facetted with facet_grid() as follows:

p <- qplot(wt, mpg, data = mtcars)
p <- p + facet_grid(. ~ vs, labeller = label_bquote(alpha^a==alpha^b))

This still works fine. However, when I add the variable on which I'm splitting to the equation in the facet label, like this:

p <- qplot(wt, mpg, data = mtcars)
p <- p + facet_grid(. ~ vs, labeller = label_bquote(alpha^a==alpha^b==.(x)))

I'm getting the following error:

Error: unexpected '==' in " p <- p + facet_grid(. ~ vs, labeller = label_bquote(alpha^a==alpha^b=="

Could someone help me out on this seemingly trivial problem?

like image 912
Luc Avatar asked Feb 15 '23 22:02

Luc


2 Answers

It's not that you're adding the variable, it's the second == that causes the problem. This is an issue with the way R parses the operators. You can control what R sees with {}:

p <- p + facet_grid(. ~ vs, labeller = label_bquote({alpha^a==alpha^b}==.(x)))

enter image description here

like image 168
alexwhan Avatar answered Feb 17 '23 11:02

alexwhan


This will work if you just add appropriate brackets.

p <- p + facet_grid(. ~ vs, labeller = label_bquote({alpha^a==alpha^b}==.(x)))
like image 44
shadow Avatar answered Feb 17 '23 12:02

shadow