naught101
naught101

Reputation: 19533

ggplot2 equivalent of matplot() : plot a matrix/array by columns?

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

Answers (3)

user3669193
user3669193

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

adibender
adibender

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

IRTFM
IRTFM

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

Related Questions