Thomas Philips
Thomas Philips

Reputation: 1089

scale_x_date not working; strange error message: Invalid input: date_trans works with objects of class Date only

I have a large dataframe which I melt and the result looks like this

> head(df_tmp)
      Date        Strategy        value
1 Jul 1986 Cum_log_act_BXM  0.000000000
2 Aug 1986 Cum_log_act_BXM -0.029465955
3 Sep 1986 Cum_log_act_BXM -0.008183544
4 Oct 1986 Cum_log_act_BXM -0.022704794
5 Nov 1986 Cum_log_act_BXM -0.026435145
6 Dec 1986 Cum_log_act_BXM -0.004544905

I'm plotting it using ggplot2, and just can't get scale_x_date to work. My dates in df_tmp are zoo yearmons,so I expect to have to convert them using as.Date, but I keep throwing an error. Here's my code:

ggplot(data = df_tmp, aes(x = Date, y = value )) +
        geom_line(aes(color = Strategy))  +
        labs(x = "Date", y = "Cumulative Log Return vs. S&P 500") +
        scale_color_manual(labels = legend_labels, values = line_colors) +
        scale_linetype_manual(values = line_types) +
        scale_x_date(limits = c(as.Date(df_tmp$Date[1]), as.Date(df_tmp$Date[nrow(df_tmp)]))) +
        theme(axis.title.x = element_text(size = 14, face = "bold"),
          axis.title.y = element_text(size = 14, face = "bold"), 
          legend.title = element_text(size = 14, face = "bold"))

The error message i get is

Error: Invalid input: date_trans works with objects of class Date only

If I remove the scale_x_date line, it works as it should, so my error must be both simple and subtle, as I do convert the yearmon's in df_tmp$Date to a date using as.Date. I just want to set the limits on the x-axis, and I'd be very appreciative for any pointers to how I might resolve my problem.

Sincerely and with many thanks in advance

Thomas Philips

Upvotes: 0

Views: 320

Answers (1)

Chris
Chris

Reputation: 2296

You clarify for ggplot that this is a zoo object and use zoo's as.Date:

class(zoo::as.Date(zoo::as.yearmon(1986 + 6/12)))
[1] "Date"

so append zoo:: in your scale_x_date call.

Upvotes: 1

Related Questions