'Using a matrix plot (matplot) as map and positions as locations

I'm interested in using a matrix plot as a field map and certain locations in matrix as specific plants (locations within field). I'm using this data:

Field<-matrix(1:1240,nrow = 40,ncol = 31)
SampTreatment<- sample(Field,6,replace = F) # Results: 388 155 582 405 1173 165
SampControl<- sample(Field,6,replace = F) # Results: 848 270 1159 1050 1177 1184

I'm trying to plot it using:

matplot(Field,col = 1,pch = 1,lty = 1)
points(SampControl,col= 'blue',pch=19,cex=1.5)
points(SampTreatment,col= 'red',pch=17,cex=1.5)

and getting:

enter image description here

The issue is that it seems the plot is not showing locations in the right place.



Solution 1:[1]

First, you may want to create your matrix like so,

n <- 6; m <- 4
(field <- matrix(seq_len(n), n, m))
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    1    1
# [2,]    2    2    2    2
# [3,]    3    3    3    3
# [4,]    4    4    4    4
# [5,]    5    5    5    5
# [6,]    6    6    6    6

and, as already suggested in comments, sample x and y coordinates. Just wrap the process in a small function.

sampfun <- \(size, mat) {
  stopifnot(size*2 <= prod(dim(mat)))
  s <- matrix(,size*2, 2, dimnames=list(NULL, c('x', 'y')))
  for (i in seq_len(size*2)) {
    repeat {
      x <- sample(ncol(mat), 1, replace=TRUE)
      y <- sample(nrow(mat), 1, replace=TRUE)
      s[i, ] <- cbind(x, y)
      if (!any(duplicated(s[1:i,,drop=FALSE]))) break
    }
  }
  return(list(treated=s[1:size, ], control=s[-(1:size), ]))
}

set.seed(42)
(samp <- sampfun(6, field))
# $treated
#      x y
# [1,] 1 5
# [2,] 1 1
# [3,] 2 4
# [4,] 2 2
# [5,] 1 4
# [6,] 3 3
# 
# $control
#      x y
# [1,] 3 4
# [2,] 4 3
# [3,] 2 1
# [4,] 2 6
# [5,] 3 6
# [6,] 4 6

Now note, that matplot transposes, so you also need to transpose. Better we use custom axises to avoid fractions.

png('test.png')

matplot(t(field), col=1, pch=1, xlab='x', ylab='y', main='Field', xaxt='n', yaxt='n')
axis(1, seq_len(ncol(field))); axis(2, seq_len(nrow(field)))
points(samp$control, col='blue', pch=19, cex=1.5)
points(samp$treated, col='red', pch=17, cex=1.5)
## optional legend
legend(par()$usr[1], par()$usr[3] - .5, legend=c('treated', 'control'), 
       col=c('red', 'blue'), pch=c(17, 19), bty='n', horiz=TRUE, cex=.9, xpd=TRUE)   

dev.off()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1