The data files have date is the format i.e. 1975M1, 1975M2, … 2011M12 for time series data. when plotting this data using R, I want the x-axis to display the months on tick axis.
For the dates to be read properly, I have tried replacing the M by – to get %Y-%m format but that doesnt seem good for drawTimeAxis from hydroTSM package which perhaps requires %Y-%M-%d format. It gives error that incorrect number of dimensions for ticks dimension.
Another method of parsing and formatting the data as in x$newdate <- strptime(as.character(x$date), "%Y-%m") and then format(x$newdate,""%Y-%m")
also doesnt read the date and gives error… all NA.
date <- as.Date(data[,1] the error that character string is not in a standard unambiguous format and ts <- read.zoo(xts, as.yearmon(x[,1])) gives bad enries at data rows.
Please give solution of how this data can be read with the date information.
A small subset of the data file
date x x2
1975M1 112.44 113.12
1975M2 113.1 114.36
1975M3 115.04 114.81
1975M4 117.65 115.35
1975M5 119.5 116.92
1975M6 121.4 118.56
1975M7 120.64 118.97
1975M8 119.12 119.84
1975M9 118.91 120.59
1975M10 120.58 122.3
1975M11 121.26 123.35
1975M12 122.34 123.33
Update: The answers so far solve the problem of reading the date correctly by using %YM%m in the xts package or adding the day for getting standard format. The customizing of tick axis is still a problem. The drawTimeAxis is giving dimension error and plot commands are not showing monthly labels for more than one year of data or otherwise . Any methods of customizing tick axis ?
Perhaps you are not using
as.yearmon()correctly, because the following works for me (usingdatfrom Gavin’s answer):Thus, working through to getting things to plot correctly:
Your data:
Conversion to
xtsusingas.yearmon()from the “zoo” package.Plotting your data:
Update: Specifying your own axes
Here is some sample data to work with (it’s usually nice to share such sample data when asking questions on SO since it makes it easier for others to replicate and address your problem(s)). Note that for this example, we’ve skipped using the “xts” package since it’s not really necessary.
This is the default plot obtained with
plot(dat.z, screen = 1, col = 1:2):From your comments, it sounds like you want something like monthly labels.
Plot the data, but suppress the x-axis with
xaxt = "n"Do some setup work to have a label for every month. (See
?plot.zoo, from where this is modified.)Add your axis to your plot. Some experimentation might be needed to find the right sizes for everything.
las = 2makes the labels perpendicular to the axis, which is required if you really feel the need to include a label for every month of each year.Here is the final plot:
By the way, if you are getting dates like
1977.15and so on, you might want to read through some of the answers to this question, for example, looking at @joran’s use ofpretty().