Question

I've a zoo object, with a yearqtr index, covering about 50 years. When plotted the x-axis shows labels every 10 years, which feels a bit barren:

b=zoo(1:200,as.yearqtr(1900+seq(1,200)/4))
plot(b)

Some study got me this:

plot(b,xaxt="n");axis(1,time(b))

Which feels like swinging from one extreme to the other, as the x-axis is a blur of ticks, with ugly fractional labels. Is there an easy way to have it just show years? (What I was looking for initially was a way to say: "lower the x-axis label spacing a bit", but there seems nothing like that? cex.axis just alters the font-size.)

Was it helpful?

Solution

Did you read help(axis)?

Here is one way, just creating a simple index every four quarters:

R> ind <- seq(1, length(b), by=4)

and using it to index the axis placement and labels:

R> plot(b,xaxt="n")
R> axis(1,time(b)[ind], format(time(b)[ind]), las=2, cex.axis=0.5)

enter image description here

I used las=2 and the lower cex value to make this fit. Once every year may still be too plenty.

Computing "good" axis labels is really hard.

OTHER TIPS

This is probably one of those (rare) situations when you want to use grid rather then ticks to better show your data. As @dirk-eddelbuettel pointed out - tweaking good axis labels is hard, especially with such density. You also might want your labels inside plot, so the grid will slightly hide their density. The easiest grid to get is with abline, unless you want to play with ggplot2, but it's uglier then standard plots in R (personal opinion). Also - make the plot wider. In fact, it's better to get rid of box around plot too ;) Below is mod of Dirk's approach:

png("strangeplot.png",width=800)
#extend y-axis to fit inside labels and remove box
plot(b,type="n",xaxt="n",yaxt="n",ylab="",xlab="",ylim=c(min(b)-30,max(b)),bty="n"))
#use 'mpg' to get labels inside
axis(1,time(b)[ind], format(time(b)[ind]), las=2, cex.axis=0.6,tick=F,mgp=c(0,-2.5,0))
axis(2,tick=F,las=1)
#you locate lines slightly to the left of label...
abline(h=seq(0,200,by=50),v=time(b)[ind]-0.5,col=gray(0.9))
#...so you need to add extra single line in the end 
abline(v=max(time(b)[ind])+0.5,col=gray(0.9))
#plot at the end to get it above grid
points(b,type="l")
dev.off() 

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top