r - 使用 R Base 从 read.csv2 读取的折线图的图例
问题描述
我有以下变量:
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
解决方案
你想使用names
:
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"
现在你可以headlines
像这样在你的图例中使用:
legend("topleft", legend = headlines,
col=c(1, 2, 3), lty = 1:2, cex=0.8)