R获得与绘图线颜色相同的图例

R get legend with same color as plot lines

嗨,我是 R 的新手,我正在尝试将多个文件绘制为散点图中的线条。我能够得到情节,但当我尝试向情节添加图例时却没有。我想要带有文件名称的图例,其颜色与从该文件生成的线条的颜色相同。我尝试使用上一个线程中的以下建议 -

xlist<-list.files(pattern = NULL)  
first=TRUE
cl <- rainbow(22)
for(i in xlist) {
    table <- read.table((i),header=T,sep="\t")  
    table <- table[, 1:2]  
    if (first) {  
        plot(table,xlab='Distance from         center',ylab='Coverage',ylim=c(0,70),col=1, type="n")  
        lines(table) #plot and add lines  
        legend("top", y=NULL, legend = i, col=1)  
        par(new=T)  
        first=FALSE   
    }  
    else {  
        lines(table,col=cl[i]) #To add another file to the plot as another line  
        par(new=F)  
        plotcol[i] <- cl[i]  
        legend("top", y=NULL, legend = i, col=plotcol)  
    }
}  

错误是 get 是 - plotcol[i] <- cl[i] 中的错误:找不到对象 'plotcol'。请让我知道我遗漏了什么,或者是否有更好的方法来绘制不同颜色的线条并获得带有与线条颜色相同的文件名称的图例。谢谢。

试试 R 中的 ggplot2 包。您也不必编写那么多代码! https://www.rstudio.com/wp-content/uploads/2015/12/ggplot2-cheatsheet-2.0.pdf

我必须制作一些可重现的示例才能使其正常工作,但以下脚本可以使长度和线条颜色相同:

#random data
test.df1=data.frame(runif(100)*0.2,runif(100)*0.2)
test.df2=data.frame(runif(100)*0.5,runif(100)*0.5)
test.df3=data.frame(runif(100),runif(100))
test.df4=data.frame(runif(100)*2,runif(100)*2)

test.list=list(test.df1=test.df1,test.df2=test.df2,test.df3=test.df3,test.df4=test.df4) # I used this instead of reading in files from read.table, you shouldn't need this

xlist=c('test.df1','test.df2','test.df3','test.df4') #the list of files

first=TRUE
cl <- rainbow(length(xlist)) #colors dedicated to your list
names(cl)=xlist #this names the vector elements so you can reference them
for(i in xlist) {
    i.table <- test.list[[i]]
    i.table <- i.table[,c(1:2)]  
    if (first) {  
        plot(i.table,xlab='Distance from center',ylab='Coverage',xlim=c(0,2),ylim=c(0,2),col=cl[i], type="n")  
        lines(i.table,col=cl[i]) #plot and add lines  
        par(new=T)  
        first=FALSE   
    }  
    else {  
        lines(i.table,col=cl[i]) #To add another file to the plot as another line  
        par(new=F)  
        plotcol <- c(plotcol,cl[i])# pulls colors from the cl vector
    }
}  

legend("top", y=NULL, legend =xlist, text.col=cl) #label colors should now match