A way to always dodge a histogram?

Updated geom_bar needs stat = "identity"

I'm not sure if this is too late for you, but see the answer to a recent post here That is, I'd take Joran's advice to pre-calculate the counts outside the ggplot call and to use geom_bar. As with the answer to other post, the counts are obtained in two steps: first, a crosstabulation of counts is obtained using dcast; then second, melt the crosstabulation.

library(ggplot2)
library(reshape2)

dat = dcast(mtcars, factor(carb) ~ factor(gear), fun.aggregate = length)
dat.melt = melt(dat, id.vars = "factor(carb)", measure.vars = c("3", "4", "5"))
dat.melt

(p <- ggplot(dat.melt, aes(x = `factor(carb)`, y = value, fill = variable)) + 
  geom_bar(stat = "identity", position = "dodge"))

The chart:

enter image description here

Tags:

R

Ggplot2