R / Zoo: Show a checkmark every year on the x axis

I have a zoo with a yearqtr index that spans about 50 years. When plotting, the x-axis shows labels every 10 years, which seems a bit fruitless:

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

Some studies have given me this:

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

Which feels swaying from one extreme to the other, since the x axis is blurring ticks, with ugly fractional marks. Is there an easy way to make it just show years? (Initially, I was looking for a way to say: “slightly reduce the distance between the labels of the x axis,” but it looks like it isn’t? Cex.axis just changes the font size.)

+4
source share
2 answers

Have you read help(axis) ?

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

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

and using it to index the placement and axis 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 a lower cex value to make this suitable. Once a year may be too much.

The calculation of the labels of a “good” axis is very difficult.

+4
source

This is probably one of those (rare) situations where you want to use a grid rather than ticks to better show your data. As @ dirk-eddelbuettel noted, setting labels with a good axis is tough, especially with such a density. You may also want your tags to be inside the plot, so the grid will slightly hide their density. The easiest grid to get is abline if you don't want to play with ggplot2, but these are uglier than the standard graphics in R (personal opinion). Also - make the plot wider. In fact, it’s better to also get rid of the box around the plot;) Below is 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

+1
source

Source: https://habr.com/ru/post/1392404/


All Articles