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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With