řggplot延伸一个类别x轴的范围(R ggplot extend the range of a

2019-09-27 00:23发布

如果我有类似下面一个数据帧

a=data.frame(year=paste('FY',2001:2012,sep='.'),values=rnorm(12))
library(ggplot2)

下图作品

ggplot(a,aes(x=year,y=values,group=1))+geom_line() 

但下面的一个没有。

ggplot(a,aes(x=year,y=values,group=1))+geom_line() +xlim(0,13)

如何延长具有类别轴,而不是一个数字一个数据的ggplot的限制?

Answer 1:

您可以使用scale_x_discretelimits参数,通过添加额外的水平c ombining这些与你原来的水平:

ggplot(a,aes(x=year,y=values,group=1))+
       geom_line() + 
       scale_x_discrete(limits=c(levels(a$year),"FY.2013"))


Answer 2:

你可以用NA增加新的因素来扩展X-范围。 这是一个有点棘手,但它的工作。 我希望别人得到更好的解决方案。

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 ggplot extend the range of a category x axis
标签: r ggplot2