在ggplot2中的facet标签中的表达式

11

我想在 ggplot2 的分面标签中使用一个 R 表达式。

假设我正在绘制 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)

enter image description here

我想将 "Female" 和 "Male" 的 facet 标签改为 "女性 受试者" 和 "男性 受试者"。据我所知,可以通过 expression 函数将标签变为斜体,但我不知道如何与 facet_wrap 结合使用。


你可以使用自定义函数,可以使用labeller参数,参见这里 - RHA
我不清楚您如何获取facet_grid的labeller参数,以替换因子并将facet放在行中,并将标签放在顶部,就像我的示例一样(而不是在facet_grid标签的侧面)。 - user1701545
你有查看这个主题吗?它可能会有所帮助。https://dev59.com/snnZa4cB1Zd3GeqPnj_5 - Boidot
很接近了,但我的标签是复合的——斜体单词后面跟着一个非斜体的单词。我不知道如何使用主题的element_text实现这一点。 - user1701545
4个回答

10

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

出现错误 Error in levels(tips$sex)[sex] : could not find function "[",某种方式bquote似乎在一个空环境中被评估?不确定这是ggplot2新版本的错误还是特性。 - jakob-r

7

看起来过于复杂,但是能够正常运行。你需要使用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)

enter image description here


我知道它必须是一个函数,但无法使其正常工作。对于为什么这在facet_wrap中不起作用,您有什么想法吗? - RHA
@RHA facet_wrap 不支持自定义标签器(我不知道为什么),但是有一种低级解决方法,如 这里 所示。 - tonytonov

3
以下内容适用于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

它使用了label_bquote,这是由@Stéphane Laurent建议的,但它不需要将级别转换为bquote内的正确字符,因为这对我而言失败了。

1

我知道这是一个旧帖子,但我喜欢label_parsed函数。它适用于factor中的标签:

data(tips, package="reshape2")
library(ggplot2)
tips %>%
  mutate(sex = factor(sex,
                      levels = c("Female", "Male"),
                      labels = c(expression(italic(Female)~Subjects), 
                                 expression(italic(Male)~Subjects)))) %>%
  ggplot(aes(x=total_bill, y=tip/total_bill)) + 
  geom_point(shape=1) + 
  facet_wrap(~sex, ncol = 1,labeller = label_parsed)

这将返回

Link to output


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接