If I have a dataframe similar to that below
a=data.frame(year=paste('FY',2001:2012,sep='.'),values=rnorm(12))
library(ggplot2)
The following graph works
ggplot(a,aes(x=year,y=values,group=1))+geom_line()
but the following one does not.
ggplot(a,aes(x=year,y=values,group=1))+geom_line() +xlim(0,13)
How can I extend the limits of a ggplot of data that has a category axis rather than a numeric one?
You can use scale_x_discrete
and the limits
parameter to add extra levels by c
ombining these with your original levels:
ggplot(a,aes(x=year,y=values,group=1))+
geom_line() +
scale_x_discrete(limits=c(levels(a$year),"FY.2013"))
You can add a new factor with NA to extend the x-range. It is a little bit tricky but it does the job. I hope someone else get better solution.
b=data.frame(year=paste('FY',2013,sep='.'),
values=NA)
a <- rbind(a,b)
ggplot(a,aes(x=year,y=values,group=1))+geom_line()