Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: mean in the function on time

Tags:

r

ggplot2

If I have data like this

DF <- data.frame(
  date = seq(Sys.Date()-1000, len=1000, by="1 day")[sample(1000, 500)],
  price = runif(500)
)

How do I plot e.g. mean of price in the function of time, e.g. in months, using ggplot2?

like image 642
atricapilla Avatar asked Jan 29 '10 10:01

atricapilla


People also ask

What does ggplot2 mean in R?

ggplot2 is a plotting package that provides helpful commands to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties.

What does Geom mean in ggplot2?

Geoms. A layer combines data, aesthetic mapping, a geom (geometric object), a stat (statistical transformation), and a position adjustment. Typically, you will create layers using a geom_ function, overriding the default position and stat if needed.

What does ggplot () do?

ggplot() initializes a ggplot object. It can be used to declare the input data frame for a graphic and to specify the set of plot aesthetics intended to be common throughout all subsequent layers unless specifically overridden.


1 Answers

You need to convert your dates into months using cut(,"months"), then apply mean to each month using ggplot stat_summary. Here's how to do it in qplot, which is a compact convenience wrapper to ggplot.

qplot(as.Date(cut(date,"months")), 
  price, data=DF, stat="summary", fun.y="mean", xlab="date")

alt text http://www.imagechicken.com/uploads/1264786975079660800.png


Base plot can also do it:

plot(aggregate(DF$price, list(as.Date(cut(DF$date, "month"))), mean))

alt text http://www.imagechicken.com/uploads/1264786673030283100.png

like image 70
Alex Brown Avatar answered Oct 12 '22 04:10

Alex Brown