繁体   English   中英

在 ggplot2 中使用带有 facet_wrap() 的不同刻度标记标记函数

[英]Use different scale tick mark labelling functions with facet_wrap() in ggplot2

我的问题与这个问题类似,但在一个重要方面有所不同。 我想使用用{scales} package 创建的不同标签函数作为刻度线标签(不是轴标签)。 这是一个可重现的例子:

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,我想使用标签 function thou而不是mill 我该怎么做? 我很确定上面链接的问题中facet_wrap()中带有labeller参数的解决方案不适用于此处,对吗?

您可能对ggh4x::scale_y_facet()感兴趣。 你给它一个方法来找到合适的面板cond == "C"并给它一个不同于默认比例的 label function。 它仅适用于自由标度的方面。 免责声明:我是 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 package (v2.0.1) 创建于 2022-11-24

如果您对自动选择的后缀感到满意,则可以使用cut_long_scale()助手 function 与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 package (v2.0.1) 创建于 2022-11-27

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM