Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotting a graph with date on the x-axis in R

Tags:

date

plot

r

I am trying to do a plot with date on x-axis with an interval of 1 month and date values rotated for clarity.

r=runif(100)
d <- as.Date("2001/1/1") + 70*sort(r)
plot(d,r,type="l",xaxt="n")
axis.Date(1, at=seq(d[1],d[100],"month"), format="%m/%d/%Y")

This doesn't really work. I am trying to get something similar to the following graph:

Reference graph

like image 812
user236215 Avatar asked Apr 10 '11 05:04

user236215


People also ask

Can you plot dates in R?

Dates Stored as Characters frame is of class character ( chr ). This means that R is reading it as letters and numbers rather than dates that contain a value that is sequential. Thus, when you plot, R tries to plot EVERY date value in your data, on the x-axis.

How do you plot a date graph?

Plotted dates are handled in the following manner: If the date field named has a month-first format, it is plotted in ascending time order (even if the file is not sorted in ascending date order). Hence, month/year values of 01/76, 03/76, 09/75 will be plotted by month within year: 09/75, 01/76, 03/76.

How does R deal with dates?

Date objects are stored in R as integer values, allowing for dates to be compared and manipulated as you would a numeric vector. Logical comparisons are a simple. When referring to dates, earlier dates are “less than” later dates.


1 Answers

It does exactly what you ask the function to do.

Three months, three ticks.

> d[1]
[1] "2001-01-01"
> d[100]
[1] "2001-03-11"

Try this.

r=runif(100)
d <- as.Date("2001/1/1") + 70*sort(r)
plot(d,r,type="l",xaxt="n")
axis.Date(1, at = seq(d[1], d[100], length.out=25),
        labels = seq(d[1], d[100], length.out=25),
        format= "%m/%d/%Y", las = 2)

It should be easily adjusted to week/month/year. It's up to you to play with the mar parameter in ?par.

like image 167
Roman Luštrik Avatar answered Sep 18 '22 10:09

Roman Luštrik