19

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))?

3 Answers 3

9

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")
Sign up to request clarification or add additional context in comments.

1 Comment

This is the best version I've seen (although still not nearly as easy as matplot, unfortunately...). Thanks!
5

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()

1 Comment

I assume there is typo: Second last line of code should be ggplot(dataL, aes_string(x="Var1", y="value", colour="Var2", group="Var2")).
2

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.