Plot multiple sets of points in R
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 pair开发者_运维技巧s:
plot(x, y, ...)
Can this function be made to take multiple sets or is there another function for that?
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")
精彩评论