将图例添加到R中的密度图
我在R中使用以下代码在一个图形上绘制两条密度曲线将图例添加到R中的密度图,r,plot,legend,R,Plot,Legend,我在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(
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()
mydata1来自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)
#比较不同车型的MPG分布
#4、6或8缸
图书馆(sm)
附加(mtcars)
#创建价值标签
我知道了。我添加了添加图例的功能!在我运行图例语句后,它给了我一个“图形设备错误”,但在用我的代码调整图例语句后,我成功地使它正确了!:)谢谢你的提醒!为什么quickR中的代码必须手动指定级别和标签?这是一个很大的工作。在我的数据集中,我有20多个级别。当我尝试做一些类似的事情(更具动态性)时,我的图例与曲线不匹配。