Search code examples
rloopscolorspolygon

loop for color and coordinate matrix objects for polygon plotting in r


Here are polygon coordinates:

# data

greenM <-matrix(c(5,5,95,45,5,65,5,45,65,5,5,95),nrow=4,byrow=TRUE)
blueM <-matrix(c(35,15,65,35,45,35,5,75,35,5,45,65,35,15,65),
 nrow=5,byrow=TRUE)
purpleM <-matrix(c(95,5,15,95,5,5,35,75,5,35,45,35,55,45,15,95,5,15),
  nrow=6,byrow=TRUE)
redM <-matrix(c(35,45,35,35,75,5,5,95,5,5,75,35,35,45,35),
 nrow=5,byrow=TRUE)
yellowM <-matrix(c(95,5,15,45,5,65,35,15,65,35,45,35,55,45,
15,95,5,15),nrow=6,byrow=TRUE)

Here is plot (unlooped, but I want to automate the long code with short so that x number of plots can be produced with x number of colors)

plot(NA,NA,xlim=c(0,10),ylim=c(0,100),asp=1,bty="n",axes=F,xlab="",ylab="")
polygon(greenM,col="green",border=NULL)
polygon(blueM,col="blue",border=NULL)
polygon(purpleM,col="purple",border=NULL)
polygon(redM,col="red",border=NULL)
polygon(yellowM,col="yellow",border=NULL)

How can I creat a look such way that, it will apply to the list of coordiantes with different colors in order.

mycolist <- list (greenM, blueM, purpleM, redM, yellowM)
col1 <- c("green", "blue", "purple", "red", "yellow")

Solution

  • Check out mapply

    mycolist <- list (greenM, blueM, purpleM, redM, yellowM)
    col1 <- c("green", "blue", "purple", "red", "yellow")
    plot(NA,NA,xlim=c(0,10),ylim=c(0,100),asp=1,bty="n",axes=F,xlab="",ylab="")
    mapply(polygon,x=mycolist,col=col1)
    

    If you don't want all the NULL output to the screen, just wrap it in invisible.

    invisible(mapply(polygon,x=mycolist,col=col1))