1

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?

4

2 回答 2

7

您可以使用scale_x_discrete和参数通过将这些与原始级别相结合limits来添加额外级别:c

ggplot(a,aes(x=year,y=values,group=1))+
       geom_line() + 
       scale_x_discrete(limits=c(levels(a$year),"FY.2013"))
于 2013-05-28T09:57:25.153 回答
4

您可以添加一个带有 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()

在此处输入图像描述

于 2013-05-28T09:24:06.860 回答