Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

plot - R:ensuring legend colors match the defined colors

I am using the R programming language. Using the famous Iris dataset, I created the following plot:

require(MASS)
cols = c('red', 'green', 'blue')
parcoord(iris[ ,-5], col = cols[iris$Species])

From here, I tried to add a legend:

legend("topright", c("setosa", "versicolor", "virginica"), lwd = 2, col = iris$Species, bty = "n")

How can I ensure that the legend colors actually match the colors on the graph? Does R automatically do this?

Thanks

question from:https://stackoverflow.com/questions/65854395/rensuring-legend-colors-match-the-defined-colors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here, the Species column of iris is a factor (try running class(iris$Species)). If you then run levels(iris$Species), you will see that the order of the levels is setosa versicolor virginica.

If you convert this factor to an integer value (try as.integer(iris$Species)), you will see that setosa = 1, versicolor = 2, and virginica = 3. When you pass cols[iris$Species] as an argument to parcoord(), you are using this factor as an index, and R silently converts it to an integer vector. Hence, setosa will map to the first element of cols, namely 'red', and so on.

Please see below:

require(MASS)
cols = c('red', 'green', 'blue')
parcoord(iris[ ,-5], col = cols[iris$Species])
legend("topright", levels(iris$Species), lwd = 2, col = cols, inset = 0.05)

This will produce the following plot:

Plot of iris data produced by above code.

While base R graphics may be sufficient for your use case, I highly recommend exploring the ggplot2 package for more advanced and customizable graphics.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...