isomorphismes
isomorphismes

Reputation: 8403

melt, not as.data.frame or rbind in R (basic ggplot)

I have several equal-length vectors of numbers, like

alpha <- c(1, 2, 3, 4)
beta <- c(5, 6, 7, 8)
gamma <- c(9, 10, 11, 12)

and I want to put these into a data frame or something with columns labelled alpha, beta, and gamma. Like

alpha | beta | gamma
1 | 5 | 9
2 | 6 | 10
3 | 7 | 11
4 | 8 | 12

which qplot should be able to read and separate out by colour = labels. cbind and rbind result in a matrix which qplot cannot read. And c lines up alpha beta and gamma, without labelling them as separate.

The diamonds data set displays what I'm after with qplot(carat, price, data = diamonds, colour = color) except I want to plot my shared-dimensional data against an index like x=1:4.

In regular R I would do plot(alpha); points(beta); points(gamma).

Sorry for asking such a basic question.

Upvotes: 0

Views: 1518

Answers (1)

kohske
kohske

Reputation: 66902

If you want a data.frame, then data.frame will do that:

> data.frame(alpha, beta, gamma)
  alpha beta gamma
1     1    5     9
2     2    6    10
3     3    7    11
4     4    8    12

And this can be passed to the qplot or ggplot.

In the case of qplot, you don't need to create data.frame. Just calling with the variables is sufficient like this:

qplot(alpha, beta, colour=gamma)

And updated after the comment.

I'm still not sure what is desired, but this example may help:

> d <- data.frame(x=1:4, alpha, beta, gamma)
> d
  x alpha beta gamma
1 1     1    5     9
2 2     2    6    10
3 3     3    7    11
4 4     4    8    12

> d2 <- melt(d, id="x")
> d2
   x variable value
1  1    alpha     1
2  2    alpha     2
... snip ...
11 3    gamma    11
12 4    gamma    12

> qplot(d2$x, d2$value, colour=d2$variable, geom="line")

# same as

> ggplot(d2, aes(x, value, colour=variable)) + geom_line()

Upvotes: 3

Related Questions