按填充子集在堆叠条中排序x轴

时间:2018-02-12 14:00:30

标签: r ggplot2

关于如何在带有ggplot2的条形图中按频率排列x轴,有多个问题(例如here)。但是,我的目标是通过填充子集的相对频率将X轴上的类别排列在堆积条形图中。例如,我想根据变量B中类别z的百分比对x轴进行排序。

这是我第一次尝试只使用ggplot2

library(ggplot2)
library(tibble)
library(scales)

factor1 <- as.factor(c("ABC", "CDA", "XYZ", "YRO"))
factor2 <- as.factor(c("A", "B"))

set.seed(43)
data <- tibble(x = sample(factor1, 1000, replace = TRUE),
               z = sample(factor2, 1000, replace = TRUE))


ggplot(data = data, aes(x = x, fill = z, order = z)) +
  geom_bar(position = "fill") +
  scale_y_continuous(labels = percent)

当这不起作用时,我使用dplyr创建了一个汇总数据框,然后传播数据并按B对其进行排序,然后再次收集它。但是密谋也不起作用。

library(dplyr)
library(tidyr)
data %>%
  group_by(x, z) %>%
  count() %>%
  spread(z, n) %>%
  arrange(-B) %>%
  gather(z, n, -x) %>%
  ggplot(aes(x = reorder(x, n), y = n, fill = z)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_y_continuous(labels = percent)

我更喜欢使用ggplot的解决方案,以便不依赖于dplyr / tidyr创建的数据框中的顺序。但是,我对任何事情持开放态度。

2 个答案:

答案 0 :(得分:2)

如果您想按绝对频率排序:

lvls <- names(sort(table(data[data$z == "B", "x"])))

如果您想按相对频率排序:

lvls <- names(sort(tapply(data$z == "B", data$x, mean)))

然后您可以在ggplot内动态创建因子:

ggplot(data = data, aes(factor(x, levels = lvls), fill = z)) +
  geom_bar(position = "fill") +
  scale_y_continuous(labels = percent)

答案 1 :(得分:0)

使用tidyverse的解决方案是:

data %>% 
  mutate(x = forcats::fct_reorder(x, as.numeric(z), fun = mean)) %>% 
  ggplot(aes(x, fill = z)) +
    geom_bar(position = "fill") +
    scale_y_continuous(labels = percent)

https://discourse-cdn-sjc1.com/business3/uploads/tidyverse/original/2X/5/588440b7c5a8df6bcb60a35b08cb22fc9f778090.png

相关问题