为ggplot堆叠的条形图升序排列每个构面

时间:2019-01-21 13:50:39

标签: r ggplot2

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())

stacked bar

上面的代码创建了堆叠的条形构面,您也可以在上面看到。每个条形图的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())

stacked bar ascending

1 个答案:

答案 0 :(得分:1)

经过一些操作,this answer变为

<transition-group>

enter image description here

与链接的答案相比,我主要对行进行排序并添加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。由于使用了scales,因此需要这样做,在这种情况下,需要手动提供颜色。

相关问题