簡體   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