Expression in ggplot2 facet labels
Looks overly complicated, but works. You'll have to use facet_grid
though.
make_label <- function(value) {
x <- as.character(value)
bquote(italic(.(x))~subjects)
}
plot_labeller <- function(variable, value) {
do.call(expression, lapply(levels(value), make_label))
}
ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_grid(.~sex, labeller = plot_labeller)
The following works for R 4.0.3 and ggplot2 3.3.2
library(ggplot2)
data(tips, package="reshape2")
tips$sex = as.character(tips$sex)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_wrap(~sex, ncol = 1, labeller = label_bquote(italic(.(sex))~subjects))
sp
It uses label_bquote
as suggested by @Stéphane Laurent but does not require converting levels into the correct character within the bquote which failed for me.
As of ggplot2
2.1.0
:
data(tips, package="reshape2")
library(ggplot2)
ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_wrap(~sex, ncol=1,
labeller=label_bquote(.(levels(tips$sex)[sex])~subjects))