Add legend to density plot in R
I'm using the following code in R to draw two density curves on a single graph;
mydata1<-read.csv(file="myfile1.csv",head=TRUE,sep=",")
mydata2<-read.csv(file="myfile2.csv",head=TRUE,sep=",")
pdf("comparison.pdf")
plot.multi.dens <- function(s)
{
junk.x = NULL
junk.y = NULL
for(i in 1:length(s)) {
junk.x = c(junk.x, density(s[[i]])$x)
junk.y = c(junk.y, density(s[[i]])$y)
}
xr <- range(junk.x)
yr <- range(junk.y)
plot(density(s[[1]]), xlim = xr, ylim = yr, xlab="Usage",main = "comparison")
for(i in 1:length(s)) {
lines(density(s[[i]]), xlim = xr, ylim = yr, col = i)
}
}
plot.multi.dens( list(mydata2$usage,mydata1$usage))
dev.off()
Now the problem is that the graph which is being produced shows two lines but the graph doesn't in开发者_StackOverflow社区clude the information that which line is which. For example, in the output, it should show that the red line is "a" and the black line is "b". I'm a newbie to R which is why i'm having some difficulty. any help will be appreciated!
Answer from quickR website
# Compare MPG distributions for cars with
# 4,6, or 8 cylinders
library(sm)
attach(mtcars)
# create value labels
cyl.f <- factor(cyl, levels= c(4,6,8),
labels = c("4 cylinder", "6 cylinder", "8 cylinder"))
# plot densities
sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")
title(main="MPG Distribution by Car Cylinders")
# add legend via mouse click
colfill<-c(2:(2+length(levels(cyl.f))))
legend(locator(1), levels(cyl.f), fill=colfill)
精彩评论