Reputation: 19533
matplot()
makes it easy to plot a matrix/two dimensional array by columns (also works on data frames):
a <- matrix (rnorm(100), c(10,10))
matplot(a, type='l')
Is there something similar using ggplot2, or does ggplot2 require data to be melted
into a dataframe first?
Also, is there a way to arbitrarily color/style subsets of the matrix columns using a separate vector (of length=ncol(a)
)?
Upvotes: 19
Views: 16417
Reputation: 49
Just somewhat simplifying what was stated before (matrices are wrapped in c() to make them vectors):
require(ggplot2)
a <- matrix(rnorm(200), 20, 10)
qplot(c(row(a)), c(a), group = c(col(a)), colour = c(col(a)), geom = "line")
Upvotes: 2
Reputation: 7568
Maybe a little easier for this specific example:
library(ggplot2)
a <- matrix (rnorm(100), c(10,10))
sa <- stack(as.data.frame(a))
sa$x <- rep(seq_len(nrow(a)), ncol(a))
qplot(x, values, data = sa, group = ind, colour = ind, geom = "line")
Upvotes: 9
Reputation: 263301
The answers to questions posed in the past have generally advised the melt strategy before specifying the group parameter:
require(reshape2); require(ggplot2)
dataL = melt(a, id="x")
qplot(a, x=Var1, y=value, data=dataL, group=Var2)
p <- ggplot(dataL, aes_string(x="Var1", y="value", colour="Var2", group="Var2"))
p <- p + geom_line()
Upvotes: 5