[R] Legend based on levels of a variable

Petr PIKAL petr.pikal at precheza.cz
Fri Apr 6 11:08:06 CEST 2012


Hi

> 
> I have a bivariate plot of axis2 against axis1 (data below). I would 
like
> to use different size, type and color for points in the plot for the 
point
> coming from different region. For some reasons, I cannot get it done. 
Below
> is my code.
> 
> col <- rep(c("blue", "red", "darkgreen"), c(16, 16, 16))
> ## Choose different size of points
> cex <- rep(c(1, 1.2, 1), c(16, 16, 16))
> ## Choose the form of the points (square, circle, triangle and
> diamond-shaped
> pch <- rep(c(15, 16, 17), c(16, 16, 16))
> 
> plot(axis1, axis2, main="My plot", xlab="Axis 1", ylab="Axis 2",
>  col=c(Category, col), pch=pch, cex=cex)
> legend(4, 12.5, c("NorthAmerica", "SouthAmerica", "Asia"), col = col,
>        pch = pch, pt.cex = cex, title = "Region")
> 
> I also prefer a control on what kind of point I want to use for 
different
> levels of Region. Something like this:
> legend(4,12.5, col(levels(Category), Asia="red", NorthAmerica="blue",
> SouthAmerica="green"))

So why you do not use Region and/or Category for automatic point 
colouring/size/type.

Without data I can only use built in one.

with(iris, plot(Sepal.Length, Sepal.Width, col= as.numeric(Species)))
legend("topright", legend=levels(iris$Species), pch=19, col=1:3)

Regards
Petr

> 
> Thanks,
> Kumar
> 
>   Region axis1 axis2  NorthAmerica 5 14  NorthAmerica 8 13  NorthAmerica 
8
> 11  NorthAmerica 6 11  NorthAmerica 5 13  SouthAmerica 8 17 SouthAmerica 
7
> 16  SouthAmerica 7 13  SouthAmerica 8 14  SouthAmerica 6 17  Asia 7 13 
Asia
> 6 15  Asia 7 14  Asia 5 13  Asia 4 16
> 
>    [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list