[英]R: reorder factor levels for several individual plots
我試圖從相同的data.frame創建幾個單獨的圖,每個圖的y軸上具有不同的因子水平順序。 每個圖都應該按y順序排列因子水平。
我知道這可以為每個情節手動完成,但我正在尋找一種更有效和更優雅的方式,因為我需要創建大量的情節。 這不必包括使用facet_wrap,如果有另一種方式,可能有循環等?
library(ggplot2)
library(dplyr)
data("diamonds")
采用數據集和聚合兩個因子水平(清晰度和切割):
means <- diamonds %>%
group_by(clarity, cut) %>%
summarise(carat = mean(carat))
在這里,我通過一個因素重新排序,但最終我想為每個圖分別重新排序(通過降低清晰度的平均值)。
means$clarity <- reorder(means$clarity, means$carat, FUN = mean)
使用face_wrap創建單獨的圖。 使用coord_flip可以更輕松地比較繪圖。
ggplot(means, aes(x = clarity, y = carat)) +
geom_col() +
facet_wrap(~cut, ncol = 1) +
coord_flip()
您將看到,這會為每種類型的切割創建單獨的圖,但y軸上的因子水平的順序對於每種情況都不正確。 如何正確訂購它們而無需為每種類型的切割手動執行此操作?
這可以通過兩個函數在一個圖中完成:
reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
new_x <- paste(x, within, sep = sep)
stats::reorder(new_x, by, FUN = fun)
}
scale_x_reordered <- function(..., sep = "___") {
reg <- paste0(sep, ".+$")
ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}
可在github dgrtwo / drlib上找到
ggplot(means, aes(x = reorder_within(clarity, carat, cut, mean), y = carat)) +
geom_col() +
scale_x_reordered() +
facet_wrap(~cut, scales = "free_y", ncol = 1) +
coord_flip()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.