Home > database >  I can't make number 10, 15, 20 and 25 to show on my plot, what is the issue with my loop?
I can't make number 10, 15, 20 and 25 to show on my plot, what is the issue with my loop?

Time:02-04

plot

code:

plot.new()
plot.window(xlim = c(0, 5), ylim = c(0, 5), asp = 1)
for (r in 0:5){
  segments(x0 = 0, y0 = r, x1 = 5, y1 = r)
}
for (c in 0:5){
  segments(x0 = c, y0 = 0, x1 = c, y1 = 5)
}
for (i in 1:25){
  if (i%%5 == 0){
    text(i - 0.5, (i%/%5-1)   0.5, labels = as.character(i))
  }else{
    text(i%%5 - 0.5, i%/%5   0.5, labels = as.character(i))
  }
}

the if statement should be able to help me place the numbers in the right col but not really working

CodePudding user response:

The problem is that you're setting the x coordinate to i - 0.5 when you hit a multiple of 5. But you really just always want that x coordinate to be 4.5.

modulo <- 5
for (i in 1:25){
  if (i %% modulo == 0){
    text(modulo - 0.5, (i%/%5 - 1)   0.5, labels = as.character(i))
    # or just text(4.5 ...)
  } else {
    text(i%%5 - 0.5, i%/%5   0.5, labels = as.character(i))
  }
}

enter image description here

CodePudding user response:

Here is a different approach without any loops or divisions:

mat <- matrix(1:25, 5, byrow=TRUE)
plot(NA, xlim=c(0, 5), ylim=c(0, 5), axes=FALSE, xlab="", ylab="")
segments(rep(0, 5), 0:5, rep(5, 5), 0:5)
segments(0:5, rep(0, 5), 0:5, rep(5, 5))
text(row(mat)-.5, col(mat)-.5 , t(mat))

Table

  •  Tags:  
  • r
  • Related