rggplot2

Fixing width for time series bar plot


I have following ggplot

library(ggplot2)
library(zoo)
dat = rbind(data.frame('Quarter' = as.yearqtr(as.Date(c('2000-01-01', '2002-01-01', '2004-01-01', '2006-01-01'))), 'Val' = c(1,2,3,4), type = rep('A', 4)), 
            data.frame('Quarter' = as.yearqtr(as.Date(c('2000-01-01',  '2004-01-01' ))), 'Val' = c(10,11), type = rep('B',2)))

ggplot(dat, aes(x = Quarter, y = Val)) +
  geom_bar(aes(fill = type), position = 'dodge', stat = 'identity', width = .5)

As you can see the width of the bars are varying despite passing argument width = .5. I have the time series data, so do not want to change the x-axis to factor.

Is there any way to fix the bar width within the present setup.


Solution

  • geom_bar(stat = "identity") was superseded by geom_col() over 7 years ago, but that's incidental here. In either case, when you use position = "dodge", setting the width argument will fix the width of each dodged group on the x axis. If there is only a single bar at some x axis positions, it will have width 0.5. If you have two bars at a position, they will both add up to 0.5 (i.e. they will each be 0.25).

    To change this you need to specify the position as position = position_dodge(preserve = "single")

    ggplot(dat, aes(x = Quarter, y = Val, fill = type)) +
      geom_col(width = 0.5, position = position_dodge(preserve = "single"))
    

    enter image description here