[R] assign same legend colors than in the grouped data plot

Jim Lemon jim at bitwrit.com.au
Thu Feb 16 10:41:46 CET 2012


On 02/16/2012 01:35 AM, agent dunham wrote:
> Dear community,
>
> I've plotted  data and coloured depending on the factor variable v3.
> In the legend, I'd like to assign properly  the same colors than in the
> factor (the factor has 5 levels).
>
> I've been trying this but it doesn't work.
>
> plot(var1, var2, xlab = "var1", ylab = "var2", col =var3 , bty='L')
> legend(locator(1),c("level 1 var3",  "level 2 var3","level 3 var3",  "level
> 4 var3","level 5 var3"), col=var3,pch=16)
>
>
Hi agent,
At a guess, your problem is that you are getting the right colors in the 
wrong order. Your legend call should probably be:

legend(locator(1),c("level 1 var3","level 2 var3","level 3 var3",
   "level 4 var3","level 5 var3"),col=as.numeric(levels(var3)),pch=16)

Then, you may get the correct colors.

Jim



More information about the R-help mailing list