As already pointed out by Mike Wise in his accepted answer, gplot2
requires a data.frame as input, preferably in long format.
However, both question and accepted answer used for
loops although R has neat functions. To create the test
data set, the following "one-liner" can been
used:
set.seed(1234L) # required to ensure reproducible data
test <- lapply(100L - 1:10, rnorm)
instead of
test <- list()
length(test) <- 10
for(i in 1:10){
test[[i]] <- rnorm(100 - i)
}
Note the use of set.seed()
to ensure reproducible random data.
To reshape test
from wide to long form, the whole list is turned into a data.frame at once using unlist()
, adding the additional columns as required:
df <- data.frame(
id = rep(seq_along(test), lengths(test)),
x = sequence(lengths(test)),
y = unlist(test)
)
instead of turning each list element into a separate small data.frame and incrementally appending the pieces to a target data.frame using a for
loop.
The plot is then created by
library(ggplot2)
ggplot(df) + geom_line(aes(x = x, y = y, color = as.factor(id)))
Alternatively, the melt()
function has a method for lists:
library(data.table)
long <- melt(test, measure.vars = seq_along(test))
setDT(long)[, rn := rowid(L1)] # add row numbers for each group
ggplot(long) + aes(x = rn, y = value, color = as.factor(L1)) + geom_line()
ggplot
is that this has to be done, and it is not really trivial until you have done it a half dozen times or so. - Mike Wisedata.frame
. - Wagner Jorge