Reputation: 161
I have a time series data for different group components. Each group ID with its various time stamps (given as Date) has an hypo and hyper response data. I would like to plot the time series for each of this group by facet (ggplot) for both (1) Group ID and also by response i.e. (2) Hyper and Hypo response so that the picture by response is one top of another. Any help is appreciated.
A demo data set and what I have done so far is given below.
set.seed(1)
tdat <- data.frame(Group = rep(paste0("GroupID-", c("A","B")),
each = 100),
Date = rep(seq(Sys.Date(), by = "1 day", length = 100), 2),
Fitted = c(cumsum(rnorm(100)), cumsum(rnorm(100))),
Signif = rep(NA, 200))
tdat <- transform(tdat, Hyper = Fitted + 1.5, Hypo = Fitted - 1.5)
## select 1 region per Site as signif
take <- sample(10:70, 2)
take[2] <- take[2] + 100
tdat$Signif[take[1]:(take[1]+25)] <- tdat$Fitted[take[1]:(take[1]+25)]
tdat$Signif[take[2]:(take[2]+25)] <- tdat$Fitted[take[2]:(take[2]+25)]
And the data frame looks like this -
> head(tdat)
Group Date Fitted Signif Hyper Hypo
1 GroupID-A 2017-04-18 -0.6264538 NA 0.8735462 -2.1264538
2 GroupID-A 2017-04-19 -0.4428105 NA 1.0571895 -1.9428105
3 GroupID-A 2017-04-20 -1.2784391 NA 0.2215609 -2.7784391
4 GroupID-A 2017-04-21 0.3168417 NA 1.8168417 -1.1831583
5 GroupID-A 2017-04-22 0.6463495 NA 2.1463495 -0.8536505
6 GroupID-A 2017-04-23 -0.1741189 NA 1.3258811 -1.6741189
The time series is given by Date.
The data I have plotted is given below. However my real data has more group ID's and I really want one picture for each group ID with splitting the image for Hyper and Hypo response.
library(ggplot2)
ggplot(tdat, aes(x = Date, y = Fitted, group = Group)) +
geom_line() +
geom_line(mapping = aes(y = Hyper), lty = "dashed") +
geom_line(mapping = aes(y = Hypo), lty = "dashed") +
geom_line(mapping = aes(y = Signif), lwd = 1.3, colour = "red") +
facet_wrap( ~ Group)
Again any help is appreciated.
Thanks
Upvotes: 1
Views: 1685
Reputation: 2060
If you will reshape
your data with reshape2
or tidyr
or data.table
and convert wide to long:
library(reshape2)
tdat2<-melt(tdat,id.vars = c("Group","Date","Signif","Fitted"))
ggplot(tdat2, aes(x = Date, y = value, group = Group)) +
geom_line() +
geom_line(mapping = aes(y = Signif), lwd = 1.3, colour = "red") +
facet_wrap( variable~ Group)
Upvotes: 7
Reputation: 33802
How about something like this, using geom_ribbon
to show the Hyper and Hypo values:
tdat %>%
ggplot(aes(Date, Fitted)) +
geom_line(lty = "dashed") +
geom_line(aes(y = Signif), lwd = 1.3, color = "red") +
geom_ribbon(aes(ymin = Hypo, ymax = Hyper, group = Group), alpha = 0.2) +
facet_grid(Group ~ .) +
theme_light()
Upvotes: 4