ggplot2 方面标签中的表达式

Expression in ggplot2 facet labels

我想在 ggplot2 方面标签中使用 R expression

假设我正在绘制 tips data.frame:

library(reshape2)
> head(tips)
  total_bill  tip    sex smoker day   time size
1      16.99 1.01 Female     No Sun Dinner    2
2      10.34 1.66   Male     No Sun Dinner    3
3      21.01 3.50   Male     No Sun Dinner    3
4      23.68 3.31   Male     No Sun Dinner    2
5      24.59 3.61 Female     No Sun Dinner    4
6      25.29 4.71   Male     No Sun Dinner    4

如下:

library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + 
         geom_point(shape=1) + 
         facet_wrap(~sex, ncol = 1)

而不是将 "Female" 和 "Male" 作为方面标签我想要: 分别为“女性 受试者”和“男性 受试者”。据我所知,R 中的斜体标签是通过 expression 函数实现的,但我不知道如何将其与 facet_wrap.

结合使用

看起来过于复杂,但有效。不过你必须使用 facet_grid

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)

截至 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))

以下适用于 R 4.0.3 和 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

它按照@Stéphane Laurent 的建议使用 label_bquote,但不需要将级别转换为 bquote 中的正确字符,这对我来说是失败的。