Set date range in ggplot

my data frame is z:

> dput(z) structure(list(Month = structure(c(14975, 15095, 15156, 15187, 15248), class = "Date"), Value = c(1, 1, 1, 6, 1)), .Names = c("Month", "Value"), row.names = c(NA, 5L), class = "data.frame") 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(breaks = "1 month", labels=date_format("%b-%Y")) 

This works fine, but I really like my data range between 1/1/2011 and 1/1/2013. My sample example is from 1/12011 to 10/1/2011. Is there an easy way to force a date range from 1/1/2011 to 1/1/2013 in ggplot?

+10
source share
3 answers

The documentation in ?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'))) 
+25
source

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

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

Update: Just received a downward movement for an unexplained reason. The code in the original question no longer works, but if you replace the call to scale_x_date (.) Only with the call to xlim () above, there will be 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

+6
source

Here is a solution using ggplot 3.1 that requires the least configuration of the source 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)) 

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

0
source

All Articles