【问题标题】:How can I reorder factors by proportion in ggplot efficiently?如何有效地在 ggplot 中按比例重新排序因子?
【发布时间】:2019-08-02 20:52:11
【问题描述】:

我的问题是我想重新排序我的 ggplot 输出中的因子,使用 geom_bar(position = "fill") 生成,以便正类的最高比例最接近 y 轴。我设法找到了一个可行的解决方案,但从我的研究来看,似乎潜伏着一个更有效的解决方案,尽管我似乎找不到它。

我已经阅读了问题Order Bars in ggplot2 bar graph,但我似乎找不到按比例排序的解决方案,即按数据框中未明确存在但作为摘要统计的值排序。

我查看了Modifying Factor Order section of the book, R for Data Science 并提出了一个解决方案,即使用“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

结果:

具有基于位置“填充”的有序因子的条形图

提前致谢。

【问题讨论】:

标签: r ggplot2 dplyr


【解决方案1】:

您可以使用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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多