简体   繁体   English

如何根据堆叠段高度控制堆叠条形图的排序?

[英]How to control ordering of stacked bar chart based on stack segment height?

I am creating a taxanomic bar chart using ggplot but I need to change the layout of the stacked segments.我正在使用 ggplot 创建分类条形图,但我需要更改堆叠段的布局。 This is my code to create the plot:这是我创建 plot 的代码:

ggplot(full_genus_new, aes(x=as.factor(Var2), y=value, fill=Var1)) +
    geom_bar(stat="identity", position = "fill", aes(order = -value)) +
    scale_x_discrete() +
    ylab("Relative Microbial Activity") +
    facet_grid(cols=vars(PEDIS), scales = "free_x", space = "free_x") +
    theme_classic() +
    scale_fill_manual(values = Cb64k) +
    scale_y_continuous(labels=percent_format()) +
    theme(legend.position = "bottom", legend.text = element_text(size=8)) +
    guides(fill=guide_legend(title="Taxa")) +
    xlab("Patient") +
    theme(legend.key.size = unit(0.5,'cm'))

Which produces the following:产生以下内容:

在此处输入图像描述

How can I reorder the stacked segments based on size so that the larger segments start at the bottom and decrease in size until the top of the y axis is reached?如何根据大小对堆叠的段重新排序,以便较大的段从底部开始并减小尺寸,直到到达 y 轴的顶部?

We can manually stack them with rectangles ordered by size:我们可以手动将它们与按大小排序的矩形堆叠:

library(ggplot2)
library(dplyr)

#example data
d <- mtcars %>% 
  group_by(am, cyl) %>% 
  summarise(s = sum(mpg)) %>% 
  mutate(s_pc = s/sum(s) * 100) %>% 
  arrange(am, -s_pc) %>% 
  group_by(am) %>% 
  mutate(ymin = cumsum(lag(s_pc, default = 0)), 
         ymax = cumsum(s_pc),
         xmin = am - 0.4,
         xmax = am + 0.4, 
         fill = factor(cyl))

#use rectangle
ggplot(d, aes(xmin = xmin, xmax = xmax,
              ymin = ymin, ymax = ymax, fill = fill)) +
  geom_rect() +
  theme_minimal()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM