user1125946
user1125946

Reputation:

Error when changing axis format with scale_x_date

Dear fellow homo sapiens,

I've created this graph using the code below (except without + scale_x_date).

The data-set that I've used to do this is found HERE. It looks like this:

GFC1CARi<-read.csv("demo.csv")
head(GFC1CARi)
  X         XX   variable       value    Var
1 1 2008-07-17 Financials 0.001772705 Financ
2 2 2008-07-18 Financials 0.017306086 Financ
3 3 2008-07-21 Financials 0.010745136 Financ
4 4 2008-07-22 Financials 0.021152194 Financ
5 5 2008-07-23 Financials 0.031195805 Financ
6 6 2008-07-24 Financials 0.026534444 Financ

As you'll see the in picture, the x-axis displays dates such as "Aug", "Sep" .... . However, I want it to be something similar to "08/2007", "09/2007" ... . So, my attempt at doing this is displayed below, but it doesn't work.

p <- ggplot(data=GFC1CARi,aes(x=XX, y=value, colour=Var)) +
        geom_line() + 
        opts(legend.position = "none") + 
        xlab(" ") + 
        ylab("Cumulative abnormal return") + 
        scale_x_date(labels = date_format("%m/%Y"),breaks = "1 month")

p <- direct.label(p+xlim(min(GFC1CARi$XX), max(GFC1CARi$XX)+20))

I've tried many other variation of breaks = ?? and date_format and I can't get the %m/%Y to show, it'll always be "Aug" .. "Sep" .. "Oct". As requested by Joran:

> str(GFC1CARi)
'data.frame':   1730 obs. of  5 variables:
 $ X       : int  1 2 3 4 5 6 7 8 9 10 ...
 $ XX      : POSIXct, format: "2008-07-17" "2008-07-18" "2008-07-21" "2008-07-22" ...
 $ variable: Factor w/ 10 levels "Financials","Industrials",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : num  0.00177 0.01731 0.01075 0.02115 0.0312 ...
 $ Var     : chr  "Financ" "Financ" "Financ" "Financ" ...

I've even tried to change the date formate from POSIXct to as.Date as follows:

GFC1CARi[,2]<-as.Date(GFC1CARi[,2])
str(GFC1CARi)
'data.frame':   1730 obs. of  5 variables:
 $ X       : int  1 2 3 4 5 6 7 8 9 10 ...
 $ XX      : Date, format: "2008-07-16" "2008-07-17" ...
 $ variable: Factor w/ 10 levels "Financials","Industrials",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : num  0.000983 0.015822 0.008339 0.017987 0.027186 ...
 $ Var     : chr  "Financ" "Financ" "Financ" "Financ" ...

This doesn't fix the situation. Instead the X-axis is now { "Oct", "Jan", "Apr" }, and that's it.

Thanks everyone.

Upvotes: 3

Views: 670

Answers (1)

joran
joran

Reputation: 173577

My apologies, I was being very dense. I thought the error you were getting was happening before the attempt to use directlabels, not after.

The call to xlim is simply stomping on the x axis formatting. Just put the scale_x_date call inside the direct.labels command works for me:

p <- direct.label(p + 
                  xlim(min(dat$XX), max(dat$XX)+20) + 
                  scale_x_date(labels = date_format("%m/%Y"),breaks = "1 month"))

enter image description here

Upvotes: 3

Related Questions