如何将匿名函数传递给ggplot的facet_wrap()中的labeller参数以将文本添加到现有标签?

问题描述 投票:0回答:1

如何将附加常量文本粘贴到 ggplot 分面标签?

例如,我现在有这样的情节:

library(ggplot2)

df <- data.frame(
  x = rnorm(120, c(0, 2, 4)),
  y = rnorm(120, c(1, 2, 1)),
  z = letters[1:3]
)

ggplot(df, aes(x, y)) + 
  geom_point() + 
  facet_wrap(~z)

创建于 2024-05-05,使用 reprex v2.0.2

现在假设我想向所有方面标签添加相同的前缀 (

Foo = 
) 字符串:

foo

如果我这样做

ggplot(df, aes(x, y)) + 
  geom_point() + 
  facet_wrap(~z, labeller = \(x) paste("foo = ", x))

我得到:

bar

如何调整传递给

labeller
的函数以显示
foo = [preexisting label]

r ggplot2
1个回答
0
投票

你必须将你的函数包装在

labeller()
中,如下所示:

library(ggplot2)

set.seed(123)

df <- data.frame(
  x = rnorm(120, c(0, 2, 4)),
  y = rnorm(120, c(1, 2, 1)),
  z = letters[1:3]
)

ggplot(df, aes(x, y)) +
  geom_point() +
  facet_wrap(~z,
    labeller = labeller(z = \(x) paste("foo = ", x))
  )

© www.soinside.com 2019 - 2024. All rights reserved.