R ggplot extend the range of a category x axis

2019-07-27 09:26发布

问题:

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?

回答1:

You can use scale_x_discrete and the limits parameter to add extra levels by combining 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"))


回答2:

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()



标签: r ggplot2