stacked geom_bar(): keep equal gaps between bars with variable widths

244 Views Asked by At

My sample data and plot:

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

enter image description here

As I wanted, width of the bar is proportional to the size of the group and height of each subgroup (low/high) is proportional to the size of this subgroup. But changing width leads to changing the gaps between the bars - how can I avoid this and keep constant distance between bars?

1

There are 1 best solutions below

1
On BEST ANSWER

You could use facet_grid and set the individual facets to have no space on left and right side

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

enter image description here