Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Label X Axis in Time Series Plot using R

Tags:

plot

r

I am somewhat new to R and have limited experience with plotting in general. I have been able to work get my data as a time series object in R using zoo, but I am having a hard time having the xaxis be labeled correctly, if it all.

When I plot my zoo object

plot(z)

The x-axis only shows one label, the year 2010. when the series is weekly spanning from April 2009 to October 2010.

I tried to convert my series back to a ts object, and even a data frame (only one column and doesn't include the dates).

Simply, how can I control the x-axis labels generally, and with time series objects?

Thanks in advance!

like image 405
Btibert3 Avatar asked Dec 04 '10 18:12

Btibert3


People also ask

How do I show X-axis values in R?

Method 1: Change Axis Scales in Base R To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do you add an X-axis title in R?

To set labels for X and Y axes in R plot, call plot() function and along with the data to be plot, pass required string values for the X and Y axes labels to the “xlab” and “ylab” parameters respectively. By default X-axis label is set to “x”, and Y-axis label is set to “y”.


1 Answers

Start with an example:

x.Date <- as.Date(paste(rep(2003:2004, each = 12), rep(1:12, 2), 1, sep = "-"))
x <- zoo(rnorm(24), x.Date)
plot(x)

If we want different tick locations, we can suppress the default axis plotting and add our own:

plot(x, xaxt = "n")
axis(1, at = time(x), labels = FALSE)

Or combine them:

plot(x)
axis(1, at = time(x), labels = FALSE)

You need to specify the locations for the ticks, so if you wanted monthly, weekly, etc values (instead of observations times above), you will need to create the relevant locations (dates) yourself:

## weekly ticks
plot(x)
times <- time(x)
ticks <- seq(times[1], times[length(times)], by = "weeks")
axis(1, at = ticks, labels = FALSE, tcl = -0.3)

See ?axis.Date for more details, plus ?plot.zoo has plenty of examples of this sort of thing.

like image 86
Gavin Simpson Avatar answered Sep 18 '22 16:09

Gavin Simpson