[英]ggplot2: mean in the function on time
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 eg mean of price in the function of time, eg in months, using ggplot2? 如何使用ggplot2绘制例如时间函数中的价格均值,例如以月为单位?
You need to convert your dates into months using cut(,"months")
, then apply mean
to each month using ggplot stat_summary
. 您需要使用
cut(,"months")
将日期转换为月份,然后使用ggplot stat_summary
将mean
应用于每个月。 Here's how to do it in qplot
, which is a compact convenience wrapper to ggplot
. 以下是如何做到这一点在
qplot
,这是一个紧凑的简便包装来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 替代文字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 alt text http://www.imagechicken.com/uploads/1264786673030283100.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.