Draw a 3x3 square grid in R

I got a list of numbers (n = 9) and I would like to display them in a 3 * 3 square grid, and fill each grid with the corresponding number. How can I do this in R without installing an additional package, for example. plotrix. Many thanks!

pic

+4
source share
3 answers

Here is a good solution using only the R base and outputting to png. Please note that the device pnghas equal width and height by default .

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 cexin a call plotto increase the number.

And you can add circles as follows. Pay attention to the abline locations.

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

, , points, .

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

, , plot, symbols text .

sample output

+3

ggplot, , :

# Setup the data
m <- matrix(c(8,3,4,1,5,9,6,7,2), nrow=3, ncol=3)
df <- expand.grid(x=1:ncol(m),y=1:nrow(m))
df$val <- m[as.matrix(df[c('y','x')])]

library(ggplot2)
library(scales)
ggplot(df, aes(x=x, y=y, label=val)) + 
  geom_tile(fill='transparent', colour = 'black') + 
  geom_text(size = 14) + 
  scale_y_reverse() +
  theme_classic() + 
  theme(axis.text  = element_blank(),
        panel.grid = element_blank(),
        axis.line  = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank())

enter image description here

+5

It uses plotrix(sorry, but it is much easier if you use the package!) And @nograpes dfdata.

library(plotrix)
xt <- xtabs(val ~ ., df[c(2,1,3)])
color2D.matplot(xt, vcex = 3, show.values = 1, axes = FALSE, xlab = "",   
                ylab = "", cellcolors = rep("white", length(xt)))

enter image description here

If other answers ever change, dfwas built with

m <- matrix(c(8,3,4,1,5,9,6,7,2), nrow = 3, ncol = 3)
df <- expand.grid(x = 1:ncol(m),y = 1:nrow(m))
df$val <- m[as.matrix(df[c('y', 'x')])]
+3
source

All Articles