ggplot2:函数中时间的平均值

发布于 2024-08-19 05:52:37 字数 203 浏览 4 评论 0原文

如果我有这样的数据,

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

如何使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

漫雪独思 2024-08-26 05:52:37

您需要使用 cut(,"months") 将日期转换为月份,然后使用 ggplot stat_summarymean 应用于每个月。以下是如何在 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


基本图也可以做到这一点:

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

替代文本http://www.imagechicken.com/uploads/1264786673030283100.png

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文