如何在R中自动生成线图图例

如何在R中自动生成线图图例,r,R,全部,, 我有以下的R脚本。值得一提的是,它基于我从中获得的脚本,并应用于我自己的数据。也许你可以告诉我,我是新的R。下面的脚本生成自动图例,并标签为1,2,3。相反,我希望脚本打印“样本名称为文本”,而不是数字。我想知道是否有人能帮我。多谢各位 # Create Line Chart fd<- read.csv ("indata", header=TRUE) ## convert factor to numeric for convenience fd$sampleN <- a

全部,, 我有以下的R脚本。值得一提的是,它基于我从中获得的脚本,并应用于我自己的数据。也许你可以告诉我,我是新的R。下面的脚本生成自动图例,并标签为1,2,3。相反,我希望脚本打印“样本名称为文本”,而不是数字。我想知道是否有人能帮我。多谢各位

# Create Line Chart
fd<- read.csv ("indata", header=TRUE)

## convert factor to numeric for convenience 
fd$sampleN <- as.numeric(fd$sampleN)
nfd <- max(fd$sampleN)

# get the range for the x and y axis 
xrange <- range(fd$gc)

#yrange <- range(fd$coverage)
yrange <- range(0,2) #you can customize this one.

# set up the plot 
plot(xrange, yrange, type="n", xlab="gc", ylab="nc" ) 
colors <- rainbow(nfd) 
linetype <- c(1:nfd) 
plotchar <- seq(18,18+nfd,1)

# add lines 
for (i in 1:nfd) { 
  tree <- subset(fd, sampleN==i) 
  lines(tree$gc, tree$coverage, type="b", lwd=1.5,
    lty=linetype[i], col=colors[i], pch=plotchar[i]) 

} 

# add a title and subtitle 
title("metrics", "")

# add a legend 
legend(xrange[1], yrange[2], 1:nfd, cex=0.8, col=colors,
     pch=plotchar, lty=linetype, title="Samples")

从图例中可以看到第三个参数(当前为
1:nfd
)是图例上显示的文本。如果您想使用标签A、B和C,可以将
1:nfd
替换为
C(“A”、“B”、“C”)

我会使用
ggplot2
来实现以下目的:

library(ggplot2)
ggplot(fd, aes(x = gc, y = coverage, color = sampleN)) + 
   geom_line()
这使用图例中的系数名称,在您的案例中是
示例度量1
,等等


你好!,我感谢你的建议。它按照您的建议工作,但我有很多数据集,我不想每次都手动输入它。当我处理不同的数据集时,我如何把它放入一个循环中,计算机自动打印出来。谢谢。我真的建议您使用
ggplot2
。语法,一旦你掌握了窍门,是非常直观的。它有一个非常广泛的情节,你可以做。
library(ggplot2)
ggplot(fd, aes(x = gc, y = coverage, color = sampleN)) + 
   geom_line()