如何将附加常量文本粘贴到 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 =
) 字符串:
如果我这样做
ggplot(df, aes(x, y)) +
geom_point() +
facet_wrap(~z, labeller = \(x) paste("foo = ", x))
我得到:
如何调整传递给
labeller
的函数以显示 foo = [preexisting label]
?
你必须将你的函数包装在
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))
)