'R - matplot x-axis not showing date inputs
I am just a beginner in R and I have a set of historical monthly yield data that looks like the sample data below:
dates rt
1 1990-01 0.0790
2 1990-02 0.0800
3 1990-03 0.0817
4 1990-04 0.0804
5 1990-05 0.0801
These data are stored in a data frame called 'data'.
I then attempt to plot the graph as follow.
#First attempt:
data <- data.frame(dates, rt)
matplot(data, type = 'l', xlab = 'month', ylab = 'US 3M rates',
main = 'US short rates 1990 - 2019')
The resulting graph showed the x-axis labels as 0, 50, 100 etc. (I have a total 350 rows of data)
#Second attempt:
data <- data.frame(dates, rt)
matplot(data, type = 'l', xlab = 'month', ylab = 'US 3M rates',
main = 'US short rates 1990 - 2019', xaxt = 'n')
axis(1, at = data$dates)
The resulting graph left the x-axis blank with the following warning/error messages:
Warning in xy.coords(x, y, xlabel, ylabel, log = log, recycle = TRUE) :NAs introduced by coercion
Warning in xy.coords(x, y, xlabel, ylabel, log) :NAs introduced by coercion
Warning in axis(1, at = data$dates) : NAs introduced by coercion
Error in axis(1, at = data$dates) : no locations are finite
#Third attempt:
data <- data.frame(dates, rt)
matplot(data, type = 'l', xlab = 'month', ylab = 'US 3M rates', main = 'US short rates 1990 - 2019', xaxt = 'n')
axis(1, at = format(data$dates, "%y-%m"))
Similarly, this also left the x-axis blank and an error message as follows:
Error in format.default(data$dates, "%y-%m") : invalid 'trim' argument
May I know how should the code be tweaked such that the x-axis can show the dates as per the sample data, i.e. showing 1990-01 and so on so forth?
Solution 1:[1]
The problem is that the dates“ column is just a character vector and you have to tell R what 1900-01` means.
The easiest way would be to convert the dates column to Date format and then to use plot instead of matplot:
data$dates <- as.Date(paste0(data$dates, "-01"))
plot(data, type = 'l', xlab = 'month', ylab = 'US 3M rates',
main = 'US short rates 1990 - 2019')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cettt |
