简体   繁体   中英

Legend appears, but it does not show color

I am using R for plotting. When my graph plots the legend appears where I want it to be but the colors are missing. mtcars 2 is a modified version of mtcars (one of the pre-loaded data sets) that adds a model and country of origin to the data set. mtcars.pca is what I named my redundance analysis (rda function under vegan), and mtcars.clust is titled for hierarchical clustering of the continuous factors of mtcars (hclust function of vegan) Below is the code I am using with mtcars2 .

示例输出

pca.fig = ordiplot(mtcars.pca, type = "none", las=1, xlim=c(-15,15), ylim = c(-20,10))        

points(pca.fig, "sites", pch = 19, col = "green", select = mtcars2$origin =="domestic")  
points(pca.fig, "sites", pch = 19, col = "blue", select = mtcars2$origin =="foreign")  

ordiellipse(mtcars.pca, mtcars2$origin, conf = 0.95, label = FALSE) 
ordicluster(mtcars.pca, mtcars.clust, col = "gray")   

legend("bottomright", title="Car Origin", c("domestic", "foreign"), col = "origin")

You need to specify a vector of colours in legend and also a pch :

library("vegan")
data(dune, dune.env)
ord <- rda(dune)
plot(ord, type = "n")
cols <- c("red","blue","green")
points(ord, col = cols[dune.env$Use], pch = 19)
legend("bottomright", legend = levels(dune.env$Use), bty = "n",
       col = cols, pch = 19)

If you don't add pch but just use col = cols legend() doesn't display any points. Because you used pch = 19 in your points() calls, use the same in the legend() call.

Also, note how to plot points of different colours in a single pass. I have some examples and explanation that go through the indexing trick I used in my code above to achieve this in a blog post of mine from a few years ago: http://www.fromthebottomoftheheap.net/2012/04/11/customising-vegans-ordination-plots/

I came to this question having the next problem in xts object: I wanted to plot all time-series in xts object with legend. Moreover, there were around 20.

  • I used (wrong):
plot(returns_xts)
addLegend(...)
  • Correct version:
plot(returns_xts, legend.loc = "bottomright", col=1:20, lty = 1)
  • There is legend.loc parameter
  • col = 1:20 generates colors for you

Result: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM