R - Adding a color legend to a plot of polygons

1.1k views Asked by At

I wanted to create sectors, then colour them, which below code does do, but I also want to add a legend to represent the spectrum of colours that have been chosen from the hues that is provided. It uses colours from the colour.heat and vector that is provided for colour always between 0 and 1, as its a ratio.

circs <- function(radii, sectors=4) {
 radii <- sort(radii)
 rads <- seq(0, 2*pi, length=2*length(radii)*sectors)# sample at these radians
do.call(rbind, lapply(radii, function(r)                   # points for drawing circles
data.frame(X=r*cos(rads), Y=r*sin(rads), 
           sector=rep(1:sectors, each=length(rads)/sectors),
           theta=rads, radius=r)))
}

drawCirc <- function(radii, sectors, hues=NULL, densities=NULL, ...) {
polys <- circs(radii, sectors)
 if (missing(hues)) {
 colors <- colorRampPalette(c("green","yellow","red","blue"))(sectors*length(radii))
 } 
else 
colors <- heat.colors(n=sectors*length(radii))
ind=0
plot(polys[,1:2], type="n" ,...)     # blank plot
for (i in seq_along(radii))  {  # add polygons
 for (j in 1:sectors) {
   ind <- ind+1
   color <- colors[ind]
  with(polys[polys$sector==j,],
       if (i == 1) {
         polygon(x=c(0, X[radius==radii[i]], 0), y=c(0, Y[radius==radii[i]], 0), 
                 col=color, density=densities[ind])
       } else
         polygon(x=c(X[radius==radii[i-1]], rev(X[radius==radii[i]])),
                 y=c(Y[radius==radii[i-1]], rev(Y[radius==radii[i]])), 
                 col=color, density=densities[ind]))
  }
 }
}

Thus when i run the following code, it draws the sectors which make up a circle.

 drawCirc(radii=1:50, sectors=24, hues=ration, main="Ratio by Colors")
 ration = c( x_1,x_2... x_3600), where each x is between 0 and 1. 

How do I create a legend to represent the colours and add it to the diagram?

I have tried, but unfortunately not been able to add the legend.

1

There are 1 answers

0
RHertel On

You can add the following lines at the very end of the function drawCirc() in your code, right before the last curly bracket is closed:

 nColors <-sectors*length(radii)
 nLegend <- 5
 legend("topleft",legend=c(formatC(rev(seq(0,1,1/(nLegend-1))),format="f",digits=2)), fill=c(colors[seq(0,nColors,nColors/nLegend)]))

Given the complexity of the code you have posted, I assume that you won't have difficulties adapting and changing the legend as you require it.

Here's the result that I obtain:

enter image description here

Hope this helps.