如何用R创建时间散点图?
数据是一系列日期和时间。
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) 为时间。我想如果同一日期有多次,我还可以添加颜色强度。
创建日期直方图非常容易。
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")
- 我还没有弄清楚如何创建轴为日期和/或时间的散点图。
- 我还希望能够拥有不需要线性日期 YYYY-MM-DD 的轴,但也可以基于 MM-DD 等月份(因此不同的年份累积),甚至可以按周轮换。
欢迎任何帮助、RTFM URI 标记或提示。
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
…
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")
- I haven't figured out yet how to create a scatterplot where the axis are date and/or time.
- I would like also to be able to have axis not necessary with linear dates YYYY-MM-DD, but also based on months such as MM-DD (so different years accumulate), or even with a rotation on weeks.
Any help, RTFM URI slapping or hints is welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ggplot2 包可以轻松处理日期和时间。
创建一些日期和时间数据:
然后获得一些 ggplot2 魔法。
ggplot
将自动处理日期,但要正确设置时间轴格式,请使用scale_y_datetime()
:关于问题的最后部分,按周分组等:要实现此目的,您可能必须将数据预先汇总到您想要的存储桶中。您可以使用
plyr
来实现此目的,然后将结果数据传递给ggplot
。The
ggplot2
package handles dates and times quite easily.Create some date and time data:
Then get some
ggplot2
magic.ggplot
will automatically deal with dates, but to get the time axis formatted properly usescale_y_datetime()
: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 toggplot
.我首先阅读有关 as.POSIXct、strptime、strftime 和 difftime 的内容。这些函数和相关函数应该允许您提取所需的数据子集。格式有点棘手,所以请使用帮助文件中的示例。
而且,一旦您的日期转换为 POSIX 类,as.numeric() 会将它们全部转换为数值,因此易于排序、绘图等。
编辑:Andre 建议使用 ggplot 来简化您的轴规格是好一个。
I'd start by reading about as.POSIXct, strptime, strftime, and difftime. These and related functions should allow you to extract the desired subsets of your data. The formatting is a little tricky, so play with the examples in the help files.
And, once your dates are converted to a POSIX class, as.numeric() will convert them all to numeric values, hence easy to sort, plot, etc.
Edit: Andre's suggestion to play w/ ggplot to simplify your axis specifications is a good one.