1
votes

I have 1000 time-series vectors and wish to plot all of them on a ggplot2 graph with the x axis ranging from (1:1000). I also want to set the alpha relatively low to see the density of certain areas.

Is there a way to do this without 1000 geom_line statements?

2
It's very likely - how about adding your data & code to make this a reproducible example?nrussell
You'll just will need to dcast::melt your data, and then it's a matter of two lines of code.David Arenburg
@DavidArenburg reshape2::meltGregor Thomas
And, as far as adding your data and code, an example with two or three time-series will be enough to generalize to 1000.Gregor Thomas
@Gregor I knew that :)David Arenburg

2 Answers

8
votes

Here is an example that demonstrates how to make a reproducible example in R, and shows how to plot 1000 lines with ggplot2:

library(ggplot2)
library(reshape2)

n = 1000
set.seed(123)

mat = matrix(rnorm(n^2), ncol=n)
cmat = apply(mat, 2, cumsum)
cmat = t(cmat)
rownames(cmat) = paste("trial", seq(n), sep="")
colnames(cmat) = paste("time", seq(n), sep="")

dat = as.data.frame(cmat)
dat$trial = rownames(dat)
mdat = melt(dat, id.vars="trial")
mdat$time = as.numeric(gsub("time", "", mdat$variable))


p = ggplot(mdat, aes(x=time, y=value, group=trial)) +
    theme_bw() +
    theme(panel.grid=element_blank()) +
    geom_line(size=0.2, alpha=0.1)

enter image description here

0
votes
library(tidyverse)

getTimeVector = function(series) {
  m = sample(seq(-300,300, 50), size = 1,
             prob = c(.02, .02, .1, .2, .1, .02, .02,
                      .1, .25, .1, .02, .03, .02))
  s = sample(c(1, 2, 5, 10), size = 1, prob=c(.5, .3, .15, .05))
  tibble(
    x = 1:1000,
    y = rnorm(1000, m, s)
  )
}

df = tibble(series = 1:1000) %>% 
  mutate(data = map(series, getTimeVector)) %>% 
  unnest(data)

df %>% ggplot(aes(x, y, group=series))+
  geom_line(size=0.1, alpha=0.1)+
  theme_bw() +
  theme(panel.grid=element_blank())

enter image description here