Search code examples
rr-grid

Draw 3x3 square grid in R


I got a list of number (n=9) and would like to draw them out in a 3*3 square grid and each grid fill with corresponding number. How can I do this in R without installing additional package e.g. plotrix. Many thanks!

pic


Solution

  • Here is a good solution using just base R, and outputting to a png. Note the default png device has equal width and height.

    png("magic_square.png")
    par(mar=c(.5,.5,.5,.5))
    plot(x=df$x,y=df$y,pch=as.character(df$val), 
         asp=1, xlim=c(0.5,3.5),ylim=c(0.5,3.5),xaxt="n",yaxt="n",xlab="",ylab="",
    xaxs="i", yaxs="i", axes=F)
    abline(v=0.5+(0:3),h=0.5+(0:3))
    dev.off()
    

    You can use cex in the plot call to make the numbers appear larger.

    And you can add circles as follows. Note the abline locations.

    symbols(1.5,1.5,circles=1,add=TRUE)
    

    And to annotate as shown in the comment, set the background of the circle and use points to draw additional text annotations.

    symbols(1.5,1.5,circles=1,bg="white",add=TRUE)
    text(x=1.5,y=1.5,labels="17",cex=3)
    

    Of course the real key to doing this well will be mastering the data structures to make calls into plot, symbols, and text efficient.

    sample output