简体   繁体   中英

R plot legend not showing colors according to points

So I have made a plot in R, with a lot of different colors indicating which of my 23 categories a point belongs to. The colors of points are added through a vector (stratumcol, which is a factor with 23 levels).

When I add the legend, trying to let that show the colors and their category, it seems they do not match (tested using ordihull, see picture below).

This is my plot code:

plot(pca_nmdsscores, type = "n")
points(pca_nmdsscores, col=stratumcol, cex=1.5, pch = 15)
legend("right","top",levels(stratumcol),cex=.8, col = as.numeric(stratumcol), pch =15, lty = 0) # pch = stratumcol
ordihull(pca_nmdsscores, groups = stratumcol,draw = "polygon", col ="purple",label = T, show.groups = "LateMoistRich")
ordihull(pca_nmdsscores, groups = stratumcol,draw = "polygon", col ="blue",label = T, show.groups = "MidWetPoor")

Here my Rplot should be visible. As you can see, my category "MaleMoistRich" connects the points with the pink-ish color, but in the legend this color is named "MidMoistRich".

The same for "MidWetPoor", connecting the mid-blue points, in the legend this color refers to "LateMoistPoor".

How do I solve this problem?

I tried looking for solutions, but didn't come across any that could solve it - including "unique" (which doesn't change anything, since my palette has been defined with 23 colors, so no need to recycle those anyway)

[Plot from R, showing legend and points color][1]

Ok - so since I'm a newbie I can't upload an image of my plot...

But see it here instead: http://i.stack.imgur.com/pzn2y.png

/thanks

Edit: The solution was to not use levels() on my factor! Not in legend = levels(stratumcol), nor in col = levels(stratumcol). Richard and DeveauP suggested levels might be the problem.

This created a new problem: my legen displayed the whole factor, not just the levels in it (but the colors corresponded to the correct point colors, which was the original problem).

this new problem was solved by using "unique()" instead of "levels()".

legend("Right","top",legend=unique(stratumcol), cex=.8, col = unique(stratumcol), pch=15, lty=0)

I found a solution

尝试

legend("right","top",legend = levels(stratumcol),cex=.8, col = levels(stratumcol), pch =15, lty = 0)

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