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?
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?
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")
Base plot can also do it:
plot(aggregate(DF$price, list(as.Date(cut(DF$date, "month"))), mean))