首页 > 解决方案 > 重新排序每个方面的升序,以获得 ggplot 堆叠条形图

问题描述

library(tidyverse)
dat <- read.table(text = "A B C
                          1   23  234 324
                          2   34  534 12
                          3   56  324 124
                          4   34  234 124
                          5   123 534 654",
                  sep = "", 
                  header = TRUE) %>% 
  gather(key = "variable", value = "value") %>% 
  group_by(variable) %>% 
  mutate(ind = as.factor(rep(1:5)), 
         perc = value / sum(value))

ggplot(dat, aes(variable, perc, fill = ind)) + 
  geom_col() +
  scale_y_continuous(labels = scales::percent_format()) + 
  facet_grid(~ variable, scales = "free_x") + 
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

堆叠条

上面的代码创建了您在上面也看到的堆叠条形刻面。每个ind条形图部分的顺序与图例上显示的相同。

我更喜欢将每个ind部分按升序(或降序)排列。多亏了@dgrtwo 和reorder_within函数,我通常可以做到这一点。

reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
  new_x <- paste(x, within, sep = sep)
  stats::reorder(new_x, by, FUN = fun)
}

但是 - 在我的例子中使用它会将上面的堆积条形图分解成下面的分解图。如何保留堆叠的条形图,并按ind升序或降序排列?

注意 - 这可能不是其他几个“在方面内重新排序”问题的重复。我一直无法找到处理堆叠条形图的问题,以及我上面描述的问题。

ggplot(dat, 
       aes(reorder_within(ind, value, variable), perc, fill = ind)) + 
  geom_col() +
  scale_y_continuous(labels = scales::percent_format()) + 
  facet_grid(~ variable, scales = "free_x") + 
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

堆叠条上升

标签: rggplot2

解决方案


经过一些操作后,这个答案变成了

dat <- dat %>% arrange(variable, -perc) %>% mutate(ordering = row_number())
aux <- with(dat, match(sort(unique(ind)), ind))
ggplot(dat, aes(x = variable, y = perc, fill = interaction(-ordering, variable))) + 
  geom_col() + facet_grid(~ variable, scales = "free_x") + 
  scale_fill_manual("ind", values = scales::hue_pal()(5)[dat$ind],
                    labels = with(dat, ind[aux]), 
                    breaks = with(dat, interaction(-ordering, variable)[aux])) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank()) +
  scale_y_continuous(labels = scales::percent_format())

在此处输入图像描述

与链接的答案相比,我主要对行进行了排序并添加了ordering. 至于恢复默认调色板,我也使用hue_pal了 from scales. 由于使用scale_fill_manual,这是需要的,在这种情况下,需要手动提供颜色。


推荐阅读