tags:

views:

378

answers:

1

I have multiple sets of xy pairs that I want to plot. I want each set of xy pairs to be connected by a line. In other words the goal is to have multiple experimental instances each approximated by a line plotted on one plot. Also how would I colour the lines differently?

The plot function does what I want, but takes on one set of xy pairs: plot(x, y, ...)

Can this function be made to take multiple sets or is there another function for that?

+4  A: 

To do this with the normal plot command, I would usually create one plot and then add more lines using the lines() function.

Otherwise you can use lattice or ggplot2. Here's some data:

df <- data.frame(a = runif(10), b = runif(10), c = runif(10), x = 1:10)

You can use xyplot() from lattice:

library(lattice)
xyplot(a + b + c ~ x, data = df, type = "l", auto.key=TRUE)

Or geom_line() in ggplot2:

library(ggplot2)
ggplot(melt(df, id.vars="x"), aes(x, value, colour = variable,
        group = variable)) + geom_line() + theme_bw()

Here's another example including points at each pair (from this post on the learnr blog):

library(lattice)
dotplot(VADeaths, type = "o", auto.key = list(lines = TRUE,
     space = "right"), main = "Death Rates in Virginia - 1940",
     xlab = "Rate (per 1000)")

And the same plot using ggplot2:

library(ggplot2)
p <- ggplot(melt(VADeaths), aes(value, X1, colour = X2,
             group = X2))
p + geom_point() + geom_line() + xlab("Rate (per 1000)") +
         ylab("") + opts(title = "Death Rates in Virginia - 1940")
Shane
I'm getting an error: Error: could not find function "dotplot" Do I need something from CRAN to use this?
hekevintran
Okay I see the library calls now. Thanks for your answer!
hekevintran