Jim Jim - 3 months ago 67
R Question

R matplot match legend color to line color

Here is my data:

name a b c
alex 25.4347 18 1.81
brian 0.14354 220 1.4
chris 51.39 1.5 1.05
david 0.8465 75 1.42
eric 1.53775 82 1.81
fred 5.74352 28.5 1.92
greg 12.91 4 1.1
henry 0.2797 100 1.35
isaac 10.14 7 1.08
jacob 0.03768 480 1.85


I'd like to plot a lines for each person, with each person having a different formula according the a, b, and c parameters.

I write this code to plot the lines:

s = seq(-60,20,by =.1)
matplot(s,t(sapply(s, function(x) ifelse(dt$name == "alex" |
dt$name == "brian" |
dt$name == "chris" |
dt$name == "david",
dt$a*((dt$b + x)^dt$c),
dt$a*((x - dt$b)^dt$c)))),
type = "l", lty = "solid", lwd = 2, ylab = "y axis label", xlab = "x axis title")

legend("left", legend = dt$name, lty=c(1,1), lwd=c(2.5,2.5), col = dt$name)


However, I can't get the legend colors to match with the line colors. I get an error saying that the first name is not a color. Any help?

Answer

You need to set col to valid colour in both matplot() and legend(). Suppose you want colour setting col_set <- rainbow(nrow(dt)), we can then do:

s = seq(-60,20,by =.1)
matplot(s,t(sapply(s, function(x) ifelse(dt$name %in% c("alex", "brian", "chris", "david"), 
                                         dt$a*((dt$b + x)^dt$c),
                                         dt$a*((x - dt$b)^dt$c)))),
        type = "l", lty = "solid", lwd = 2, ylab = "y axis label",
        xlab = "x axis title", col = col_set)

legend("left", legend = dt$name, lty=c(1,1), lwd=c(2.5,2.5), col = col_set)

enter image description here

Also note how I replace your long == with a single %in%.