4

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?

Vasily A
  • 8,256
  • 10
  • 42
  • 76
  • 1
    It seems like you're basically trying to make a mosaic plot, such as [here](https://stackoverflow.com/questions/19233365/how-to-create-a-marimekko-mosaic-plot-in-ggplot2) – camille Aug 26 '19 at 20:12
  • you're right, that's exactly what I wanted, thank you! Aesthetically, I like better how the output with `facet_grid` solution looks - and also the fact that I don't need additional function for it - but it definitely deserves to be added as an answer. – Vasily A Aug 26 '19 at 20:26

1 Answers1

2

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

d.b
  • 32,245
  • 6
  • 36
  • 77
  • 1
    that's a nice workaround, thanks! (I will keep the question open for some time, to see if someone suggests more "native" solution) – Vasily A Aug 26 '19 at 20:08