为R中的x值指定名称

时间:2014-09-08 11:48:45

标签: r plot time-series axis

我需要为百分比增长时间序列图的x值指定某些名称。我知道如何删除值,但我想要名称“08-09 q1”,“08-08 q2”,“08-09 q3”,“08-09 q4”,“09-10 q1”,... ,“14-15 q2”来替换它们,使x轴上的每个值都直接低于绘制的点。我怎样才能做到这一点?

plot.ts(percentagegrowth1,xaxt="n",xlab="Quarter",ylab="Percentage growth",main="Year-over-Year Quarterly Percentage Growth") 

for(i in 1:length(percentagegrowth1r))  
{
  text(x=i,y=percentagegrowth1r[i],labels=percentagegrowth1r[i],cex=0.5,font=2,pos=1)  
  text(x=i,y=percentagegrowth1r[i],labels=percentagegrowth1r[i],cex=0.5,font=2,pos=3)
} 

lines(percentf1,col="red")  
points(percentagegrowth1r,col="blue")  
dates<-c(1.1,1.2,1.3,1.4,2.1,2.2,2.3,2.4,3.1,3.2,3.3,3.4,4.1,4.2,4.3,4.4,5.1,5.2,5.3,5.4,6.1,6.2,6.3,6.4,7.1,7.2) 

for(i in 1:length(dates)) { 
  axis(1,at=i,labels=dates[i]) 
} 

legend("topright",c("x-values=Year comparison.Quarter e.g 1.1=08-09 q1","Red=Forecasted data"))  
  

percentagegrowth1r =
  -37.1 9.6 -8.9 71.8 111.8 106.4 65.4 68.8 53.0 40.6 22.5 36.9 30.8 14.5 23.6 38.3 16.1 29.2 39.0 4.0 -6.3 46.0 32.7 32.8 72.4 13.5
  percentf1 =   NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 32.67955 32.78714 72.44055 13.48962

这是我绘制的图表的图像:

enter image description here

我想将值1.1替换为“08-09 q1”,1.2替换为“08-08 q2”,1.3替换为“08-08 q3”,1.4替换为“08-09 q4”,2.1替换为“09-10 q1”,...,7.1替换为“14-15 q1”,7.2替换为“14-15 q2”

2 个答案:

答案 0 :(得分:1)

问题似乎是生成给定年份和季度的标签。怎么回事:

yr=function(i){paste(sprintf("%02d-%02d",i,i+1))}

让我们生成任意年份标签:

yr(6:14)
[1] "06-07" "07-08" "08-09" "09-10" "10-11" "11-12" "12-13" "13-14" "14-15"
季度很简单:

qlabels =
function(yrs){
  q = rep(1:4, length(yrs))
  sprintf("%s q%s", rep(yr(yrs),rep(4,length(yrs))), q)
}
制造

> qlabels(8)
[1] "08-09 q1" "08-09 q2" "08-09 q3" "08-09 q4"
> qlabels(8:10)
 [1] "08-09 q1" "08-09 q2" "08-09 q3" "08-09 q4" "09-10 q1" "09-10 q2"
 [7] "09-10 q3" "09-10 q4" "10-11 q1" "10-11 q2" "10-11 q3" "10-11 q4"

然后添加轴标签,将序列缩短,因为你以q2结束:

> plot.ts(percentagegrowth1r,xaxt="n",xlab="Quarter",ylab="Percentage growth",main="Year-over-Year Quarterly Percentage Growth") 
> axis(1,1:length(dates), qlabels(8:14)[1:26])

axis没有绘制所有值,因为它们不适合没有重叠。您可以调整cex参数:

> plot.ts(percentagegrowth1r,xaxt="n",xlab="Quarter",ylab="Percentage growth",main="Year-over-Year Quarterly Percentage Growth") 
> par(cex=0.5)
> axis(1,1:length(dates), qlabels(8:14)[1:26])

detail of tiny labels

答案 1 :(得分:0)

我找到了答案,以防其他人遇到同样的问题:)

首先为绘制的矢量中的每个数字指定一个名称:

names(percentagegrowth1)<-c("08-09 q1","08-09 q2","08-09 q3","08-09 q4","09-10 q1","09-10 q2","09-10 q3","09-10 q4","10-11 q1","10-11 q2","10-11 q3","10-11 q4","11-12 q1","11-12 q2","11-12 q3","11-12 q4","12-13 q1","12-13 q2","12-13 q3","12-13 q4","13-14 q1","13-14 q2","13-14 q3","13-14 q4","14-15 q1","14-15 q2")

然后绘制图表:

plot.ts(percentagegrowth1,xaxt="n")

然后分配x值:

axis(1,at=seq(1,length(percentagegrowth1),by=1),labels=names(percentagegrowth1))