我在R中使用以下代码在单个图形上绘制两条密度曲线;
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()
现在的问题是正在生成的图表显示了两行,但图表中没有包含哪一行的信息。例如,在输出中,它应该显示红线是“a”而黑线是“b”。我是R的新手,这就是我遇到困难的原因。任何帮助将不胜感激!
答案 0 :(得分:1)
来自quickR网站的回答
# 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)