Home > database >  ggplot fails to plot time series when width is provided
ggplot fails to plot time series when width is provided

Time:06-01

I have below ggplot with time series data

library(ggplot2)
dat = data.frame('date' = as.Date(c('2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01', '2004-01-01', '2005-01-01', '2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01', '2004-01-01', '2005-01-01')), 'val' = 1:12, 'sep' = rep(c('sep1', 'sep2'), each = 6))
ggplot(dat, aes(x = date, y = val))  
geom_bar(aes(fill = sep), stat = 'identity', position = 'dodge', width = 0.8)  
scale_x_date(date_labels =  "%Y")

With this I ma getting some strange plot

enter image description here

It looks that if I dont provide information width = 0.8 then plot appears fine. Is there any way to adjust the width of each bar?

CodePudding user response:

As @Rajan said right in the comments make your width bigger and you can use date_breaks = "1 year" to label al your bars like this:

library(ggplot2)
dat = data.frame('date' = as.Date(c('2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01', '2004-01-01', '2005-01-01', '2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01', '2004-01-01', '2005-01-01')), 'val' = 1:12, 'sep' = rep(c('sep1', 'sep2'), each = 6))
ggplot(dat, aes(x = date, y = val))  
  geom_bar(aes(fill = sep), stat = 'identity', position = 'dodge', width = 100)  
  scale_x_date(date_breaks = "1 year", date_labels =  "%Y")  
  labs(x = "Year")

Output:

enter image description here

  • Related