set date range in ggplot

It would be a courtesy to SO users to note that you have in addition to 'ggplot2' also loaded the scales package. There is an ggplot2::xlim function, so this works:

  ...... + xlim(as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y") )

Update: Just got a downvote for an unexplained reason. The code in the original question no longer works, but if you replace the scale_x_date(.) call with just the xlim() call above there is no error.

ggplot(z, aes(Month, Value)) + 
     geom_bar(fill="orange",size=.3,  stat="identity", position="identity") +
     geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
     xlim(as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y") )

enter image description here


Here's a solution using ggplot 3.1 which requires the least tweaks to the original code:

ggplot(z, aes(Month, Value)) + 
    geom_bar(fill="orange",size=.3, stat="identity", position="identity") +
    geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
    scale_x_date(date_breaks = "1 month", 
           limits = as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y"),
           date_labels="%b-%Y" ) +
    theme(axis.text.x = element_text(angle = 90))

the theme() at the end is optional, but makes the formatting easier to read if you want to use your original "%b-%Y" formatting string.


The documentation at ?scale_x_date mentions that it accepts all "typical" continuous scale arguments, including limits:

library(scales)
ggplot(z, aes(Month, Value)) + 
    geom_bar(fill="orange",size=.3,  stat="identity", position="identity") + 
    geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
    scale_x_date(date_breaks = "1 month", 
                 labels=date_format("%b-%Y"),
                 limits = as.Date(c('2011-01-01','2013-01-01')))

Tags:

Date

R

Ggplot2