【问题标题】:Add legend to density plot in R将图例添加到 R 中的密度图
【发布时间】:2011-11-30 01:29:51
【问题描述】:

我在 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 的新手,这就是为什么我遇到了一些困难。任何帮助将不胜感激!

【问题讨论】:

  • 我明白了。我添加添加图例功能!

标签: r plot legend


【解决方案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)

【讨论】:

  • 在我运行图例语句后,它给了我一个“图形设备错误”,但在用我的代码调整图例语句后,我设法把它弄对了!:) 感谢您的提醒!跨度>
  • 为什么来自 quickR 的代码必须手动指定级别和标签?这是很多工作。在我的数据集中,我有 20 多个级别。当我尝试做类似的事情(更动态)时,我的图例与曲线不匹配。
猜你喜欢
  • 1970-01-01
  • 2015-11-08
  • 1970-01-01
  • 2019-08-04
  • 2020-08-21
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多