Why the legend is not correct in R

812 views Asked by At

I am trying regression with modified iris dataset using msgps package in R:

iris2 = iris
iris2$Species = as.numeric(iris2$Species)
str(iris2)
    'data.frame':   150 obs. of  5 variables:
     $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
     $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
     $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
     $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
     $ Species     : num  1 1 1 1 1 1 1 1 1 1 ...

library(msgps)
fit = msgps(as.matrix(iris2[1:4]), iris2$Species)
plot(fit, criteria='cp')
legend('topleft', names(iris2[1:4]), lty=1:4, col=1:4) 

enter image description here

The legend is clearly wrong. It has a dashed red line which is not there in the main graph. The main graph has a light blue line which is not there in the legend. Where is the problem? Thanks for your help.

1

There are 1 answers

1
ila On

I'm not certain but my guess would be that your code legend(... lty=1:4, col=1:4) only changes the colors and line types in the legend, and not the plot itself. I would try putting that code in the plot() function as well. This is to ensure R knows that the col and lty values are synced in the plot function and the legend function.