plot having different color for different year - R

Viewed 226

How to have the same color for each year using the following matrix (for example, three lines that I have for 1011, I want to have all in red). I have tried plot(All[,1:2],col=1:4) which gives different color for each point in the plot. Any idea how to solve it?

Appreciate!

structure(c(1564.7, 1310.72727272727, 1063.46153846154, 1164.77777777778, 
1284.52941176471, 868.214285714286, 2610.83333333333, 929.47619047619, 
1121.2, 3130.6, 2110.77272727273, 3600.54545454545, 2096.96296296296, 
1688.91666666667, 1371.03846153846, 12610.4, 14047.6363636364, 
11548.2857142857, 14474.3333333333, 16720.9411764706, 15759.5714285714, 
18197.4166666667, 9571.80952380952, 6553, 11778.4, 11159.2727272727, 
12094.2727272727, 11003, 8450.25, 9756.46153846154, 15.6, 17.5454545454545, 
13.7142857142857, 15.1111111111111, 17.4705882352941, 16.3571428571429, 
19.4166666666667, 13.0952380952381, 10.4, 17.8, 16.6363636363636, 
18, 15.8888888888889, 11.25, 13.1538461538462, 1011, 1011, 1011, 
1112, 1112, 1112, 1112, 1213, 1213, 1213, 1213, 1314, 1314, 1314, 
1314), .Dim = c(15L, 4L), .Dimnames = list(NULL, c("NumAct", 
"TR", "Gr", "Year")))
2 Answers

The Year values can be accessed using All[,4] and passing that as col argument will give you a color based on the values of that column.

plot(All[,1:2],col=All[,4]) 

output

test_out

Update

To add legend, you can do the following (I can explain if you want one):

legend("topleft", legend=names(table(ALL[,4])), pch=1, col=unique(names(table(ALL[,4]))))

Output - 2

output_update

For adding legend you can use the following code though it is a manual one but works fine

Plotting

plot(All[,1:2],col=c("coral4","springgreen4","magenta","black"),pch=19) 

Add a legend

legend(locator(1),legend=c("1011","1112","1213","1314"),col=c("coral4","springgreen4","magenta","black"),pch=19,bty="n",cex=c(0.8,0.8,0.8,0.8))

[1]: https://i.stack.imgur.com/5VrBk.png

Related