ggplot时间序列绘图:按日期分组 [英] ggplot time series plotting: group by dates

查看:620
本文介绍了ggplot时间序列绘图:按日期分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一个面板图上绘制几个时间序列,而不是单独的面板。我从



当消除 facet_grid()部分时,我会看到如下所示的图形:





基本上,我希望ggplot忽略日期的差异,只考虑时间。然后使用 group 来确定不同的日期。



这个问题可以通过创建一个新列来解决只包含时间(例如 22:01 format =%H:%M)。然而,当使用 as.POSIXct()函数时,我得到一个包含日期和时间的变量。由于数据文件对于每个组的时间都有不同的日子,因此我们可以使用单向的方法来解决这个问题。

把所有的小组放到同一个小区里,就是创建一个新的变量,给所有的小组使用相同的虚拟日期,但是使用实际收集到的时间。

 实验<  -  data.frame(Time,Value,Group)#创建数据框
实验$ hms < - as.POSIXct(paste(2015-01-01, substr(experiment $ Time,12,19)))#将假日期2015-01-01粘贴到时间HMS上

现在你有了所有相同日期的时间,然后你可以轻松地绘制它们。

  experiment $ Grouping<  -  as.factor(experiment $ Group)#gglot needed Group是一个因子,根据Group 
给出线条颜色ggplot(aes(x = hms,y = Value,color = Grouping ))+ geom_line(size = 2)

以下是生成的图像(可以更改/ mo不同的基本情节,你认为适合):


I would like to plot several time series on the same panel graph, instead of in separate panels. I took the below R code from another stackoverflow post.

Please note how the 3 time series are in 3 different panels. How would I be able to layer the 3 time series on 1 panal, and each line can differ in color.

Time = Sys.time()+(seq(1,100)*60+c(rep(1,100)*3600*24, rep(2, 100)*3600*24, rep(3, 100)*3600*24))
Value = rnorm(length(Time))
Group = c(0, cumsum(diff(Time) > 1))

library(ggplot2)
g <- ggplot(data.frame(Time, Value, Group)) + 
 geom_line (aes(x=Time, y=Value, color=Group)) +
 facet_grid(~ Group, scales = "free_x")

If you run the above code, you get this:

When the facet_grid() part is eliminated, I get a graph that looks like this:

Basically, I would like ggplot to ignore the differences in the dates, and only consider the times. And then use group to identify the differing dates.

This problem could potentially be solved by creating a new column that only contains the times (eg. 22:01, format="%H:%M"). However, when as.POSIXct() function is used, I get a variable that contains both date and time. I can't seem to escape the date part.

解决方案

Since the data file has different days for each group's time, one way to get all the groups onto the same plot is to just create a new variable, giving all groups the same "dummy" date but using the actual times collected.

experiment <- data.frame(Time, Value, Group)  #creates a data frame
experiment$hms <- as.POSIXct(paste("2015-01-01", substr(experiment$Time, 12, 19)))  # pastes dummy date 2015-01-01 onto the HMS of Time

Now that you have the times with all the same date, you then can plot them easily.

experiment$Grouping <- as.factor(experiment$Group)  # gglot needed Group to be a factor, to give the lines color according to Group
ggplot(experiment, aes(x=hms, y=Value, color=Grouping)) + geom_line(size=2)

Below is the resulting image (you can change/modify the basic plot as you see fit):

这篇关于ggplot时间序列绘图:按日期分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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