jeffrey
jeffrey

Reputation: 3354

How can I format my Dates using as.Date() in R?

I have a dataset that looks like this:

Date        AE      AA      AEF     Percent
1/1/2012    1211    1000    3556    0.03
1/2/2012    100     2000    3221    0.43
1/3/2012    3423    10000   2343    0.54
1/4/2012    10000   3000    332     0.43
1/5/2012    2342    500     4435    0.43
1/6/2012    2342    800     2342    0.23
1/7/2012    2342    1500    1231    0.12
1/8/2012    111     2300    333 
1/9/2012    1231    1313    3433    
1/10/2012   3453    5654    222 
1/11/2012   3453    3453    454 
1/12/2012   5654    7685    3452    

I am trying to plot this set with ggplot, but ggplot does not plot the dates in order because they are not numeric. I am trying to convert the dates using as.Date().

library(ggplot2)
data <- read.csv("GCdataViz/test2.csv")
newDates <- as.Date(data$Date)
ggplot(data, aes(x = newDates, y = Percent)) + 
  geom_point(size = 3)  

However, the date plots are not what I expected them to be. Whereas the dataset is all January data (mm/dd/yyyy), I see different months in the ggplot.

Can anyone reproduce this and diagnose the problem? Thanks.

Upvotes: 0

Views: 2201

Answers (2)

Irsal
Irsal

Reputation: 156

ggplot does not necessarily interpret dates well. Have you tried transforming the data into a timeseries

Something like:

# Make data a time series, starting Jan 2009
data.ts<-ts(data, start=c(2009,1),frequency=52)

Then plot it using ggplot.

Upvotes: 1

Dirk is no longer here
Dirk is no longer here

Reputation: 368539

Read help(as.Date) -- you need to supply a format string as well:

R> as.Date(c("1/1/2001", "1/2/2001", "1/3/2001"), "%m/%d/%Y")
[1] "2001-01-01" "2001-01-02" "2001-01-03"
R> 

Upvotes: 2

Related Questions