[R] Legend based on levels of a variable

Petr PIKAL petr.pikal at precheza.cz
Fri Apr 6 12:14:42 CEST 2012


Thanks, 

anyway, using build-in R features is preferable for colours

with(data, plot(axis1, axis2, col= c("red", "blue", 
"green")[as.numeric(data$Region)]))
legend("topright", legend=levels(data$Region), fill= c("red", "blue", 
"green"))

although sometimes can be preferable to get advantage of grid graphic

library(ggplot2)
p<-ggplot(data, aes(x=axis1, y=axis2, colour=Region))
p+geom_point()

Regards
Petr

> 
> He provided data, yet in an inconvenient way at the bottom of his post.
> 
> Kumar, please use dput() to provide data to the list, because its much
> easier to import:
> dput(data)    ## name data is made up by me
> 
> structure(list(Region = structure(c(2L, 2L, 2L, 2L, 2L, 3L, 3L, 
> 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L), .Label = c("Asia", "NorthAmerica", 
> "SouthAmerica"), class = "factor"), axis1 = c(5L, 8L, 8L, 6L, 
> 5L, 8L, 7L, 7L, 8L, 6L, 7L, 6L, 7L, 5L, 4L), axis2 = c(14L, 13L, 
> 11L, 11L, 13L, 17L, 16L, 13L, 14L, 17L, 13L, 15L, 14L, 13L, 16L
> )), .Names = c("Region", "axis1", "axis2"), class = "data.frame", 
row.names = c(NA, 
> -15L))
> 
> 
> 
>    [[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