简体   繁体   English

R添加图例

[英]R add legend to plot

I wrote the following script to generate several plot in a for loop which works well: 我编写了以下脚本,以在效果良好的for循环中生成多个图:

stat <- list.files("D:/...", pattern = "met")

par(mfrow = c(4, 4))
for (x in stat) {
plot((assign(x, read.csv(x, head=TRUE, sep=""))),typ="l", col="red")
}

What I would like to achieve now is to add the title of each graph recursively according to the name of the file that is read. 我现在想要实现的是根据所读取文件的名称以递归方式添加每个图形的标题。

Hope this is clear, 希望这很清楚,

Best, 最好,

PS I also have another curiosity but I will leave this maybe for after. PS我也有另一个好奇心,但我可能会留待以后。

Thanks. 谢谢。

Does adding the title ( main ) argument to plot do what you're looking for? 添加title( main )参数以进行plot是否可以满足您的需求?

plot((assign(x, read.csv(x, head=TRUE, sep=""))),typ="l", col="red", main=x)

edited for OPs comment 编辑OP评论

you can use gsub for this. 您可以为此使用gsub

plot((assign(gsub('\\.txt', '', x), 
      read.csv(x, head=TRUE, sep=""))),
     typ="l", 
     col="red", 
     main=gsub('\\.txt', '', x))

However, the looping assign construct you're using is a dangerous one to get in the habit of using. 但是,您正在使用的循环分配构造是一种使用习惯的危险。 Usually this would be done by reading all the files in as a list and then lapply across them, or some variation on that theme. 通常,这可以通过以列表形式读取所有文件,然后对它们进行lapply或对该主题进行一些变体来完成。

You should be able to skip the assign step altogether unless you're doing additional processing after this plot step. 除非在该绘图步骤之后进行其他处理,否则您应该可以完全跳过assign步骤。

plot(read.csv(x, head=TRUE, sep=""),
     typ="l",
     col="red",
     main=gsub('\\.txt', '', x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM