Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display dates on axes in R

Tags:

plot

r

I have a data frame df contains 2 fields (Number and dates) as the following

Number  date
1496    Apr-08
3067    May-08
3049    Jun-08
3077    Jul-08
3237    Aug-08
3020    Sep-08
4990    Oct-08
4776    Nov-08
5140    Dec-08
5582    Jan-09
5743    Feb-09
5561    Mar-09
5974    Apr-09

I want to use plot() function in R to plot number vs. date I've tried using axis.Date() function but it didn't work. Nothing displayed on the plotting area and I don't know why. My code was:

plot(df$Number)
axis.Date(1, at=seq(min(df$date), max(df$date), by="months"), format="%m-%Y")

Any help, please?

like image 272
sarashaker Avatar asked May 03 '17 08:05

sarashaker


2 Answers

It seems that your biggest problem is creating an appropriate date structure for your data. It would be good to acquaint yourself to the different ways that R keeps the date structure. ?strptime has a rather good list of syntax commonly used.

In your question then, to convert your date to a form which axis.Date can work, you need to add an arbitrary day into your date field and then convert it with as.Date:

df$date <- as.Date(paste0("01-", df$date), format="%d-%b-%y")

This way, your axis.Date plot would work:

plot(df$date, df$Number, xaxt="n")
axis.Date(1, at=seq(min(df$date), max(df$date), by="months"), format="%m-%Y")

enter image description here

Input data:

df <- structure(list(Number = c(1496, 3067, 3049, 3077, 3237, 3020, 
4990, 4776, 5140, 5582, 5743, 5561, 5974), date = c("Apr-08", 
"May-08", "Jun-08", "Jul-08", "Aug-08", "Sep-08", "Oct-08", "Nov-08", 
"Dec-08", "Jan-09", "Feb-09", "Mar-09", "Apr-09")), .Names = c("Number", 
"date"), row.names = c(NA, -13L), class = "data.frame")
like image 139
Adam Quek Avatar answered Sep 30 '22 16:09

Adam Quek


The likely source of your problem is that df$date is not a date, but e.g. a character.

Using

str(df)
'data.frame':   13 obs. of  2 variables:
 $ Number: int  1496 3067 3049 3077 3237 3020 4990 4776 5140 5582 ...
 $ date  : chr  "Apr-08" "May-08" "Jun-08" "Jul-08" ...
# note that date is a character vector here, as opposed to Date.

and

plot(df$Number)
axis(1, at=1:nrow(df), labels=df$date)

I get

enter image description here

like image 36
coffeinjunky Avatar answered Sep 30 '22 17:09

coffeinjunky