如何用 R 创建时间散点图? [英] How to create a time scatterplot with R?

查看:21
本文介绍了如何用 R 创建时间散点图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据是一系列日期和时间.

The data are a series of dates and times.

date time
2010-01-01 09:04:43
2010-01-01 10:53:59
2010-01-01 10:57:18
2010-01-01 10:59:30
2010-01-01 11:00:44
…

我的目标是用横轴 (x) 上的日期和纵轴 (y) 上的时间来表示散点图.我想如果同一日期有不止一次,我也可以添加颜色强度.

My goal was to represent a scatterplot with the date on the horizontal axis (x) and the time on the vertical axis (y). I guess I could also add a color intensity if there are more than one time for the same date.

创建日期直方图非常容易.

It was quite easy to create an histogram of dates.

mydata <- read.table("mydata.txt", header=TRUE, sep=" ")
mydatahist <- hist(as.Date(mydata$day), breaks = "weeks", freq=TRUE, plot=FALSE)
barplot(mydatahist$counts, border=NA, col="#ccaaaa")

  1. 我还没有弄清楚如何创建一个以日期和/或时间为轴的散点图.
  2. 我还希望能够使用线性日期 YYYY-MM-DD 而不需要轴,但也可以基于诸如 MM-DD 之类的月份(因此不同的年份会累积),甚至可以在几周内轮换.

欢迎任何帮助、RTFM URI 拍打或提示.

Any help, RTFM URI slapping or hints is welcome.

推荐答案

ggplot2 包非常容易处理日期和时间.

The ggplot2 package handles dates and times quite easily.

创建一些日期和时间数据:

Create some date and time data:

dates <- as.POSIXct(as.Date("2011/01/01") + sample(0:365, 100, replace=TRUE))
times <- as.POSIXct(runif(100, 0, 24*60*60), origin="2011/01/01")

df <- data.frame(
  dates = dates,
  times = times
)

然后获得一些 ggplot2 魔法.ggplot 将自动处理日期,但要正确格式化时间轴,请使用 scale_y_datetime():

Then get some ggplot2 magic. ggplot will automatically deal with dates, but to get the time axis formatted properly use scale_y_datetime():

library(ggplot2)
library(scales)
ggplot(df, aes(x=dates, y=times)) + 
  geom_point() + 
  scale_y_datetime(breaks=date_breaks("4 hour"), labels=date_format("%H:%M")) + 
  theme(axis.text.x=element_text(angle=90))

关于您问题的最后一部分,按周分组等:要实现这一点,您可能必须将数据预先汇总到您想要的存储桶中.您可以为此使用 plyr,然后将结果数据传递给 ggplot.

Regarding the last part of your question, on grouping by week, etc: To achieve this you may have to pre-summarize the data into the buckets that you want. You can use possibly use plyr for this and then pass the resulting data to ggplot.

这篇关于如何用 R 创建时间散点图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆