【问题标题】:stacked geom_bar(): keep equal gaps between bars with variable widths [duplicate]堆叠的geom_bar():在可变宽度的条之间保持相等的间隙[重复]
【发布时间】:2019-08-26 19:41:51
【问题描述】:

我的样本数据和绘图:

library(data.table)
library(ggplot2)

dt2 <- fread('
risk group counts
low  A     178
High A     1
low  B     4
High B     100
low  C     45
High C     83
low  D     50
High D     2
             ')
# ggplot(dt2, aes(x=group,y=counts,fill=risk)) + geom_bar(stat='identity')

dt2[,rel1:=counts/sum(counts),by=group]
# ggplot(dt2, aes(x=group,y=rel1,fill=risk)) + geom_bar(stat='identity')

dt2[,grpSize:=sum(counts),by=group]
ggplot(dt2, aes(x=group,y=rel1,fill=risk,width = grpSize/200)) + geom_bar(stat='identity')

如我所愿,条形的宽度与组的大小成正比,每个子组的高度(低/高)与该子组的大小成正比。但是更改 width 会导致条形之间的间隙发生变化 - 我怎样才能避免这种情况并保持条形之间的距离不变?

【问题讨论】:

  • 看来您基本上是在尝试制作马赛克图,例如here
  • 你说得对,这正是我想要的,谢谢!从美学上讲,我更喜欢 facet_grid 解决方案的输出外观 - 以及我不需要额外功能的事实 - 但它绝对值得作为答案添加。

标签: r ggplot2 mosaic-plot marimekko-chart


【解决方案1】:

您可以使用facet_grid 并将各个方面设置为左右两侧没有空间

graphics.off()
ggplot(dt2, aes(x=group,y=rel1,fill=risk,width = grpSize/200)) +
    geom_bar(stat='identity') +
    scale_x_discrete(expand = c(0, 0)) +
    facet_grid(~group, scales = "free", space = "free")

【讨论】:

  • 这是一个很好的解决方法,谢谢! (我会将这个问题保持一段时间,看看是否有人提出更“原生”的解决方案)
猜你喜欢
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2019-10-31
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多