Is it possible to have variable width of bars in geom_col?

Viewed 820

There is an option to change fill and col when using geom_col Is it possible to have change width of bars in geom_col - like in the last line below ?

dt <- data.table(diamonds) [ , .(total=.N, price = mean(price)), by = cut]; dt # data.table to work with

ggplot(dt) + geom_col(aes(x=cut, y=price, fill=total))   # we can do this
ggplot(dt) + geom_point(aes(x=cut, y=price, size=total)) # we can do this

ggplot(dt) + geom_col(aes(x=cut, y=price, size=total))   # this does something different
ggplot(dt) + geom_col(aes(x=cut, y=price, width=total))  # this does not work

Or what could be a way to achieve the desired output - I need the width of bars be proportional to the total.
This is quite a typical situation: when you plot anything about data - you need to show the sample size of these data

2 Answers

Try this:

library(ggplot2)
library(data.table)

ggplot(dt) + 
  geom_col(aes(x=cut, y=price), width = dt$total/100000)

Vary the denominator to the width argument to vary the absolute width of the columns.

Created on 2020-06-13 by the reprex package (v0.3.0)

I accepted the answer above, based on which the code below is written that does that job as needed - by moving the width argument inside aesthetics:

dt %>% ggplot(dt) + 
  geom_col( aes(x=cut, y=price, width = total/max(total)) )

This is nice because then you can call it in pipeline using %>%, as you don't need to specify dt$ inside the function.

Note however that this generates the warning Warning: Ignoring unknown aesthetics: width (using ggplot2_2.2.1 version), but it does do the job.

enter image description here

Related