如何用R创建时间散点图? [英] How to create a time scatterplot with R?
问题描述
日期时间
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掌or或提示。
<
ggplot2
包很容易处理日期和时间。 创建一些日期和时间数据:
日期< - as.POSIXct(as.Date(2011 / 01/01)+样本(0:365,100,取代= TRUE))
次< - as.POSIXct(runif(100,0,24 * 60 * 60),origin =2011/01 / 01)
df< - data.frame(
日期=日期,
次数=次数
)
然后获得一些 ggplot2
魔法。 ggplot
会自动处理日期,但为了正确格式化时间轴,请使用 scale_y_datetime()
:
pre $ c $ library $ g
$ g $ )+
geom_point()+
scale_y_datetime(breaks = date_breaks(4小时),labels = date_format(%H:%M))+
theme(axis.text。 x = element_text(angle = 90))
关于你的最后一部分问题,按星期分组等等:为了实现这一点,您可能需要将数据预先汇总到您想要的存储桶中。您可以使用 plyr
作为结果,然后将结果数据传递给 ggplot
。
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.
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
)
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))
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屋!