Reputation: 39
I'm having problems plotting a time series using ggplot2. I am relatively new to R and cannot figure out why R cannot execute my code. I get the following error: Invalid input: date_trans works with objects of class Date only
. What exactly is this error trying to tell me? I've Googled this error before, and there doesn't seem to be an explanation of what this error means, just code to eliminate the error.
I have two columns of data in a text file which I read into R. One column contains dates (e.g., in this type of format: 8/1/10). The other contains numerical values that I want to plot against the date. The dates are at the monthly scale (e.g., 8/1/10, 9/1/10, 10/1/10).
Here is the code I've used to try to plot a time series of this data (my dataframe has been assigned to df26
):
ggplot(df26, aes(df26$Mo_Yr, df26$Vol_Tot)) +
geom_line() +
scale_x_date(labels=date_format("%b-%y")) +
xlab("Date") +
ylab("Total Volume")
Any help would be appreciated!
Here is some sample data from my dataframe (df26):
Mo_Yr Vol_Tot
8/1/10 691254
9/1/10 610358
10/1/10 629178
11/1/10 569872
12/1/10 531769
1/1/11 459966
2/1/11 428976
3/1/11 555656
4/1/11 570110
5/1/11 614337
6/1/11 661598
7/1/11 717756
8/1/11 693103
9/1/11 610873
10/1/11 613217
11/1/11 564546
Upvotes: 0
Views: 7149
Reputation: 78650
Your Mo_Yr
column is not of class Date
. However, even more importantly, it's not formatted the way R needs a date to be formatted. (I'm guessing from context that it goes M/D/Y, but R doesn't know that).
The lubridate
package (which you'd have to install) is a good way to parse a date from a format. In your case:
library(lubridate)
library(scales)
library(ggplot2)
# the important line:
df26$date <- as.Date(parse_date_time(df26$Mo_Yr, "%m/%d/%y"))
print(ggplot(df26, aes(date, Vol_Tot)) +
geom_line() +
scale_x_date(labels=date_format("%b-%y")) +
xlab("Date") +
ylab("Total Volume"))
Upvotes: 3