ggplot time series plotting: group by dates

2019-07-03 04:30发布

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:

enter image description here

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

ggplot bad graph

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.

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-03 05:12

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): enter image description here

查看更多
登录 后发表回答