Add legend with color and range in R -


the following example code produces color dot graph according values of a :

a <- sample(1:100) rbpal <- colorramppalette(c('red','blue')) b <- rbpal(10)[as.numeric(cut(a,breaks = 10))] plot(a,col=b,pch=16) 

i add legend graph indicating range of values colors refer to. like:

 "#c60038" - [20.7 - 30.7]  "#5500aa" - [60.4 - 70.3] 

(the above color code colored dots).

you can save cut() levels separate variable function levels(). function gsub() can replace , - , ( [. in function legend() provide position of legend, variable cuts use labels, col=rbpal(10) use same 10 colors in legend , pch=16 make filled dots.

cuts<-levels(cut(a,breaks = 10)) cuts<-gsub(","," - ",cuts) cuts<-gsub("\\(","[",cuts) cuts  [1] "[0.901 - 10.8]" "[10.8 - 20.7]"  "[20.7 - 30.7]"  "[30.7 - 40.6]"  "[40.6 - 50.5]"  "[50.5 - 60.4]"  "[60.4 - 70.3]"   [8] "[70.3 - 80.3]"  "[80.3 - 90.2]"  "[90.2 - 100]"   plot(a,col=b,pch=16) legend("top",cuts,col=rbpal(10),pch=16) 

enter image description here


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

Macromedia Director: Decompile EXECUTABLE File -