Specifying first and last tags with ggplot2 using scale_x_date

I would like to be able to indicate the first and last marks that appear on the graph created by ggplot2, but encounter some problems. Here is the code.

#Produce a vector of days dateVec<-seq(from=as.Date("2011-11-21"), to=as.Date("2012-11-23"), by="days") #Some randome data myData<-rnorm(length(dateVec)) #Plot it qplot(dateVec, myData) + scale_x_date(breaks="4 weeks", limits=c(min(dateVec), max=max(dateVec)))+ theme(axis.text.x=element_text(size=10, angle=45, colour="black", vjust=1, hjust=1)) 

Please note that the minimum date in the date vector is 2011-11-21, and the maximum date is 2012-11-23, and that I have indicated the limits of the graph. However, the plot seems somewhat enlarged.

Is there a way to make the first and last mark marks correspond to the actual constraints specified in scale_x_date?

Thanks!

+6
source share
1 answer

To prevent the axis from being expanded, you can add the argument expand=c(0,0) to scale_x_date() .

 qplot(dateVec,myData) + scale_x_date(breaks="4 weeks",limits=c(min(dateVec),max=max(dateVec)),expand=c(0,0)) + theme(axis.text.x = element_text(size=10,angle=45,colour="black",vjust=1,hjust=1)) 

enter image description here

UPDATE

If you need ticks starting with minimum and maximum dates, you can define your own breaks. To do this, I made a break.vec vector containing the minimum and maximum dates, as well as dates by month between them. He then used this vector to set gaps in scale_x_date() .

 break.vec<-c(as.Date("2011-11-21"), seq(from=as.Date("2011-12-01"), to=as.Date("2012-11-01"), by="month"), as.Date("2012-11-23")) qplot(dateVec,myData) + scale_x_date(breaks=break.vec) + theme(axis.text.x = element_text(size=10,angle=45,colour="black",vjust=1,hjust=1)) 

enter image description here

+11
source

All Articles