使用R Base从read.csv2读取折线图的Legens

使用R Base从read.csv2读取折线图的Legens,r,R,我有以下变量: res = read.csv2(text = "X-Years;Y-Halden;Y-Moss;Y-Sarpsborg 2020;31373;49273;56732 2030;32839;51918;59261 2040;34292;54535;61214 2050;35345;56632;62598") 我想要标题只是因为我想把它们添加到一个乐章中,如下所示: legend("topleft", legend=c("Line

我有以下变量:

res = read.csv2(text = "X-Years;Y-Halden;Y-Moss;Y-Sarpsborg
2020;31373;49273;56732
2030;32839;51918;59261
2040;34292;54535;61214
2050;35345;56632;62598")
我想要标题只是因为我想把它们添加到一个乐章中,如下所示:

legend("topleft", legend=c("Line 1", "Line 2", "Line 3"),
       col=c(1, 2, 3), lty = 1:2, cex=0.8)
其中第1行=Y-Halden,第2行=Y-Moss,第3行=Y-Sarpsborg

我试过这个,但只产生了几年:

res = read.csv2(text = "X-Years;Y-Halden;Y-Moss;Y-Sarpsborg
2020;31373;49273;56732
2030;32839;51918;59261
2040;34292;54535;61214
2050;35345;56632;62598")

headlines = res[ ,0:1]
headlines
[1] 2020 2030 2040 2050
您想使用
名称

headlines = names(res)
headlines

[1] "X.Years"     "Y.Halden"    "Y.Moss"      "Y.Sarpsborg"
如果您想摆脱
X.Years

headlines = names(res)[-1]
headlines

[1] "Y.Halden"    "Y.Moss"      "Y.Sarpsborg"
现在您可以在图例中使用
标题
,如下所示:

legend("topleft", legend = headlines,
       col=c(1, 2, 3), lty = 1:2, cex=0.8)