【问题标题】:Expression in ggplot2 facet labelsggplot2 刻面标签中的表达式
【发布时间】:2015-12-16 17:59:37
【问题描述】:

我想在 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)

我不希望将“女性”和“男性”作为分面标签: 分别为“女性科目”和“男性科目”。据我所知,在 R 中将标签斜体化是通过 expression 函数实现的,但我不知道如何将其与 facet_wrap 结合使用。

【问题讨论】:

  • 您可以使用自定义函数,可以与 labeller 参数一起使用,请参阅here
  • 我不清楚你是如何获得 facet_grid 的 labeller 参数来用表达式替换因子并在行中使用标签在顶部的方面,如在我的示例中(而不是在侧面如行的 facet_grid 标签)。
  • 你检查过这个话题吗?这可能会有所帮助stackoverflow.com/questions/20037843/…
  • 很接近,但我的标签是复合的——一个斜体字后跟一个非斜体字。我不知道如何使用主题的 element_text 实现这一目标

标签: r ggplot2 label facet-wrap


【解决方案1】:

截至ggplot22.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 版本的功能。
【解决方案2】:

看起来过于复杂,但确实有效。不过你必须使用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)

【讨论】:

  • 我知道它必须是一个函数,但无法让它工作。关于为什么这不适用于 facet_wrap 的任何想法?
  • @RHA facet_wrap 不支持自定义贴标机(我不知道为什么),但有一个低级解决方法,如 here 所示。
【解决方案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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多