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

smci
  • 32,567
  • 20
  • 113
  • 146
naught101
  • 18,687
  • 19
  • 90
  • 138

3 Answers3

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")
adibender
  • 7,288
  • 3
  • 37
  • 41
  • This is the best version I've seen (although still not nearly as easy as `matplot`, unfortunately...). Thanks! – bnaul Feb 19 '13 at 20:09
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()
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 1
    I assume there is typo: Second last line of code should be `ggplot(dataL, aes_string(x="Var1", y="value", colour="Var2", group="Var2"))`. – MYaseen208 Aug 21 '12 at 06:49
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")