Plotting multive curves in R
I need to plot multi curves in a single graph in R, for example (a,b) and (a,c) in t开发者_StackOverflow社区he same graph, where a,b and c are data vectors. Anyone know how to do this? Thanks.
cheng
You can do this using the plot
and lines
commands:
x <- 1:10
y1 <- 1:10
y2 <- 0.5 * y1
#Set up the plot
plot(range(x),range(c(y1,y2)),type="n")
#Create the lines
lines(x,y1)
lines(x,y2)
@joran's suggestion is a good one. Another option is to use matplot
after cbinding the y
-values (working on @joran's example):
matplot(x, cbind(y1, y2))
This has the added advantage of not having to find ranges and similar yourself.
Check ?matplot
for lots of options.
If b and c are matrix columns, matplot
(and matlines
for adding further lines) can be used, too:
a <- 1 : 10
bc <- matrix (c (a, a / 2), ncol = 2)
matplot (a, bc, type = "l")
ggplot2 easily supports this by mapping columns in a data.frame to aesthetics. I find it easiest to use melt
from reshape(2) to generate data in the appropriate format for these tasks. ggplot handles setting the colours, defining an appropriate legend, and lots of the other details that make plotting annoying at times. For example:
library(ggplot2)
dat <- melt(data.frame(x = x, y1 = y1, y2 = y2), id.vars = "x")
ggplot(dat, aes(x, value, colour = variable)) + geom_line()
精彩评论