我的问题与这个问题类似,但在一个重要方面有所不同。我想使用通过包创建的不同标签函数作为刻度线标签(而不是轴标签)。这是一个可重现的示例:{scales}
library(ggplot2)
library(scales)
mill <- number_format(scale = 1/1000000, suffix = " M")
thou <- number_format(scale = 1/1000, suffix = " k")
df <- data.frame(cond = rep(c("A", "B", "C"), each = 5),
x_unit = rep(1:5, 3),
y_unit = round(c(rnorm(5, 5e6, 10000),
rnorm(5, 5e6, 10000),
rnorm(5, 5000, 1000))))
ggplot(df, aes(x = x_unit, y = y_unit)) +
geom_line() +
scale_y_continuous(labels = mill) +
facet_wrap(~ cond, scales = "free_y")
Run Code Online (Sandbox Code Playgroud)
您可能已经明白我的意思了:对于 C 面,我想使用标签函数thou而不是mill。我该怎么做呢?我很确定上面链接的问题labeller中的参数解决方案facet_wrap()不适用于此处,对吗?
您可能感兴趣ggh4x::scale_y_facet()。您可以为其提供一种找到适当面板的方法cond == "C",并为其提供与默认比例不同的标签功能。它仅适用于没有尺度的小平面。免责声明:我是 ggh4x 的作者。
library(ggplot2)
library(scales)
mill <- number_format(scale = 1/1000000, suffix = " M")
thou <- number_format(scale = 1/1000, suffix = " k")
df <- data.frame(cond = rep(c("A", "B", "C"), each = 5),
x_unit = rep(1:5, 3),
y_unit = round(c(rnorm(5, 5e6, 10000),
rnorm(5, 5e6, 10000),
rnorm(5, 5000, 1000))))
ggplot(df, aes(x = x_unit, y = y_unit)) +
geom_line() +
scale_y_continuous(labels = mill) +
facet_wrap(~ cond, scales = "free_y") +
ggh4x::scale_y_facet(cond == "C", labels = thou)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v2.0.1)于 2022 年 11 月 24 日创建