躲闪的条形图,带有堆栈总数 [英] dodged bar chart with stack for the total

查看:35
本文介绍了躲闪的条形图,带有堆栈总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个躲避的条形图中添加一个堆积的条形图,以显示总数.我不希望总计列为实心条,而是由堆叠的组件组成.我可以将两个geom_bars都添加到绘图中,但是我无法移动总计条形图.我可以在中间添加一个零虚拟类别,但是我当然希望总数在组件的右侧.

  df = data.frame(treatment = rep(c("Impact","Control")),类型= rep(c("Phylum1","Phylum2"),每个= 2),总数= c(2,3,4,5))ggplot(df,aes(y = total,x = treatment,fill = type))+geom_bar(position = position_dodge(),stat ="identity",alpha = 0.9,width = 0.25)+geom_bar(position = position_stack(),stat ='identity',alpha = 0.3,width = 0.125) 

I would like to add a stacked bar to a dodged bar chart, showing the total. I don't want the column for the total to be a solid bar, but to consist of the stacked components. I can add both geom_bars to the plot, but I haven't been able to move the total bar. I could add a dummy category with zero in the middle, but of course I'd prefer the total to be to the right of the components.

df=data.frame(
    treatment=rep(c("Impact","Control")),
    type=rep(c("Phylum1","Phylum2"),each=2),
    total=c(2,3,4,5))

ggplot(df,aes(y=total,x=treatment,fill=type)) + 
    geom_bar(position= position_dodge(),stat="identity", alpha = 0.9, width = 0.25) +
    geom_bar(position = position_stack(), stat = 'identity', alpha = 0.3, width = 0.125) 

This is not the same question they want to stack/dodge by two variables. I just want to summarise the same info twice, but differently.

I can of course add a bar for the solid total and put in the stacked bar by hand, but I get so close with basic ggplot that I thought maybe a little hack (e.g. modifying the return object of position_stack) might be possible.

解决方案

You could reshape your dataset and use facets to get the effect, although this will show all of your data and not just the largest value in each type/treatment combination.

Your dataset would need to be repeated twice, once for the the original type and once for plotting the totals. You also need a new variable, which I called type2.

df$type2 = df$type
df2 = df
df2$type2 = "Total"

Stack the two datasets together via rbind, and then plot using type2 as the x variable and the alpha variable.

ggplot(rbind(df, df2), aes(y = total, x = type2, fill = type, alpha = type2)) + 
    geom_col(width = .9) +
    facet_wrap(~treatment, strip.position = "bottom") +
    scale_alpha_manual(values = c(.9, .9, .3), guide = "none") +
    theme(strip.background = element_blank(),
          axis.text.x = element_blank(),
          axis.ticks.length = unit(0, "mm"),
          panel.spacing = unit(0, "mm"),
          panel.grid.major.x = element_blank()) +
    scale_x_discrete(expand = c(1, 0))

这篇关于躲闪的条形图,带有堆栈总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆