簡體   English   中英

如何在ggplot中按比例重新排列因子?

[英]How can I reorder factors by proportion in ggplot efficiently?

我的問題是我想對使用geom_bar(position = "fill" )生成的ggplot輸出中的因子進行重新排序,以便使正類的最高比例最接近y軸。 我設法找到了一個可行的解決方案,但是從我的研究看來,似乎有一個更有效的解決方案潛伏,盡管我似乎找不到。

我已經閱讀了ggplot2條形圖中的“訂購酒吧 ”問題但似乎找不到按比例訂購的解決方案,即按數據框中未明確顯示的值進行匯總,而是匯總統計信息。

我看過《 數據科學的R》一書的“ 修改因子順序”部分,並提出了一種解決方案,其中使用“ prop”列生成摘要數據框,並使用fct_reorder2()從這些值創建折線圖。 但是,我似乎無法對“填充”條形圖應用類似的邏輯。

我最終偶然發現的解決方案來自這個來源#267 REORDER A VARIABLE IN GGPLOT2 ,您只需使用mutate()設置新的因子水平。 但是,我不僅創建了自己的順序,還創建了一個數據框,該框按正類的比例對因子進行排序。

我想知道的是,是否有一種更有效的方法(也許在長管操作中)?

這是一個可重現的示例:

library(ggplot2)
library(dplyr)

variable <- c(rep("alpha", 4),
              rep("beta", 4),
              rep("gamma", 4),
              rep("delta", 4))

class <- c(rep("1", 4),
           "1", "1", "0", "0",
           rep("0", 3), "1",
           rep("1", 3), "0")

dframe <- data.frame(variable, class)

plot_order <- dframe %>%
  count(variable, class) %>%
  group_by(variable) %>%
  mutate(prop = prop.table(n)) %>%
  filter(class == "1") %>%
  arrange(prop)

lvls <- as.character(plot_order$variable)

dframe %>%
  mutate(variable = factor(variable, levels = lvls)) %>%
  ggplot(aes(x = variable, fill = class)) +
  geom_bar(position ="fill") +
  labs(y = "Proportion")

這是plot_order的輸出:

# A tibble: 4 x 4
# Groups:   variable [4]
  variable class     n  prop
  <fct>    <fct> <int> <dbl>
1 alpha    1         4  1   
2 delta    1         3  0.75
3 beta     1         2  0.5 
4 gamma    1         1  0.25

結果:

帶有基於位置“填充”的有序因子的條形圖

帶有基於位置“填充”的有序因子的條形圖

提前致謝。

您可以從forcats包中使用fct_reorder 您在鏈接的第一個問題中也多次提到該軟件包:

# data
dframe <- data.frame(
  variable = rep(c("alpha", "beta", "gamma", "delta"), each = 4),
  class = c(rep("1", 4),
            "1", "1", "0", "0",
            rep("0", 3), "1",
            rep("1", 3), "0"))

dframe %>%
  # convert variable to a factor, ordered (in descending order) by the proportion of
  # rows where the class == "1"
  mutate(variable = forcats::fct_reorder(.f = variable, 
                                         .x = class,
                                         .fun = function(.x) mean(.x == "1"),
                                         .desc = TRUE)) %>%
  ggplot(aes(x = variable, fill = class)) +
  geom_bar(position = "fill") +
  labs(y = "Proportion")

情節

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM