[英]Reformat label / preserve order of Multi-factor facets in ggplot2::facet_wrap() based on factor level
我希望基於兩個因素對圖形進行構面,使用兩個構面因素值的組合重命名構面,但根據原始因素中的水平保留構面的順序。
數據看起來像這樣:
library(tidyverse)
set.seed(100)
tmp.d <- data.frame(
sector = factor(rep(c("B","A"),c(6,3)), levels = c("B","A")),
subsector = factor(rep(c("a","b","c"), each = 3), levels = c("c","b","a")),
year = factor(rep(2020:2022,3)),
value = sample(8:15,9, replace = TRUE)
)
#> tmp.d
# sector subsector year value
#1 B a 2020 9
#2 B a 2021 14
#3 B a 2022 13
#4 B b 2020 15
#5 B b 2021 10
#6 B b 2022 8
#7 A c 2020 9
#8 A c 2021 13
#9 A c 2022 11
這是按部門和子部門繪制和分面的...
ggplot(tmp.d, aes(x = year, y = value, group = 1)) +
geom_path()+
facet_wrap(facets = list("sector","subsector"))
...看起來像這樣:
請注意,構面保持由“部門”和“子部門”的因子水平設置的順序。 這是可取的。
但是,我不想在單獨的行上列出扇區和子扇區,而是希望分面標簽讀取“[扇區]:[子扇區]”,如“B:b”。
嘗試1:
向 tmp.d 添加一個幫助列,其中包含構面標簽。
tmp.d <- tmp.d %>% mutate(label = factor(paste0(sector, ": ", subsector)))
ggplot(tmp.d, aes(x = year, y = value, group = 1)) +
geom_path()+
facet_wrap(facets = list("label"))
產生:
在這里,方面標簽是正確的,但我已經失去了部門/子部門因素水平的順序。
嘗試2:
我認為答案可能在於自定義as_labeller
function 或者甚至可能更改現有貼標器的設置,例如label_value
,它具有multi_line = [bool]
屬性,用於控制構面值是出現在單行還是多行上。 label_
系列的其他版本有另一個屬性sep =
我相信它控制着值在同一行中的分隔方式。 據推測, ...multi_line = FALSE, sep = ": "...
的組合可能會格式化 label 並保留所需的順序。
貼標機應用於對facet_wrap()
的調用。
ggplot(tmp.d, aes(x = year, y = value, group = 1)) +
geom_path()+
facet_wrap(facets = list("sector","subsector"), labeller = [the labeller function])
將貼標機設置為現有貼標機 function 而不更改默認設置(見下文)會產生與我上面最初嘗試相同的 output。
...
facet_wrap(facets = list("sector","subsector"), labeller = label_value)
...
嘗試像這樣更改 label_value 的屬性值...
...
facet_wrap(facets = list("sector","subsector"), labeller = label_value(multi_line = FALSE))
...
...不起作用,因為label_value
function 需要我不知道如何提供的label
值。 將方面因素作為名稱或字符串(作為列表或向量)傳遞似乎不起作用。 我在文檔或其他地方找到的示例使用facet_grid
而不是facet_wrap
,並且labels
提供為像~sector+subsector
這樣的公式,我假設它被視為網格/矩陣,其中扇區是列,子扇區是行。 在我的情況下,大多數(但不一定是全部)部門/子部門的組合將是唯一的(即,部門 A 和 B 不共享子部門)。
問題摘要
有沒有一種簡單的方法來實現我的目標(為方便起見重述):
謝謝,
哇,這比我預期的要復雜得多......一種解決方案是將它們組合到不同的領域:
tmp.d |>
arrange(sector, subsector) |> # arrange by factor levels
mutate(
facet =
paste0(sector, ": ", subsector) |>
fct_inorder(ordered = TRUE) # use that order for the new field
) |>
ggplot(aes(x = year, y = value, group = 1)) +
geom_path()+
facet_wrap(facets = ~facet) # here
如果“,”是可以接受的,這也有效:
ggplot(tmp.d, aes(x = year, y = value, group = 1)) +
geom_path()+
facet_wrap(
facets = sector~subsector,
labeller =
labeller( # here
sector = label_value, #
subsector = label_value, #
.multi_line = FALSE #
)
)
可以用purrr::partial()
完成類似的事情,它會替換默認值,但你會再次得到一個逗號。 我認為值得在他們的 github 頁面上創建一個問題,以向label_*()
函數添加一個sep
參數
... +
facet_wrap(
facets = sector~subsector,
labeller = purrr::partial(label_value, multi_line = FALSE)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.