在 ggplot2 中使用 facet_wrap() 函数时,如何使用不同的刻度标记标签函数?

5

我的问题与这个问题类似,但在一个重要方面略有不同。我想使用{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")

你可能已经看出我想说什么了:对于 C 维度,我想使用标签函数 thou 而不是 mill。该怎么做呢?我相信我在上面链接的问题中提到的使用 facet_wrap() 中的 labeller 参数的解决方案在这里不适用,对吗?

示例输出

2个回答

5
你可能会对ggh4x::scale_y_facet()感兴趣。您可以为其提供一个方法来查找适当的面板cond == "C",并提供与默认比例不同的标签函数。它仅适用于自由刻度的facet。免责声明:我是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)

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


1
太棒了,它很有效,感谢您的回答,特别是感谢您对该软件包的工作! - swolf

1
如果您满意自动选择后缀,可以使用cut_long_scale()辅助函数,该函数可与scale_cut选项一起使用。与手动定义刻度相比的优点是,您不必事先知道不同数字范围的数量级。
library(ggplot2)
library(scales)

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 = number_format(scale_cut = cut_long_scale())) +
  facet_wrap(~ cond, scales = "free_y")

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


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