r - 使用矩阵图 (matplotlib) 作为 map ,使用位置作为位置

标签 r matrix plot mapping

我有兴趣使用矩阵图作为田野 map ,并将矩阵中的某些位置用作特定植物(田野内的位置)。 我正在使用这些数据:

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

我正在尝试使用以下方法绘制它:

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)

并得到:

enter image description here

问题是绘图似乎没有在正确的位置显示位置。

最佳答案

首先,您可能想像这样创建矩阵,

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

并且,正如评论中已经建议的,sample x 和 y 坐标。只需将流程包装在 small 函数中即可。

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

现在请注意,matplot 会转置,因此您还需要t转置。更好的是,我们使用自定义轴来避免分数。

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

关于r - 使用矩阵图 (matplotlib) 作为 map ,使用位置作为位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72208945/

相关文章:

r - 如何从 Sys.info() 中提取用户名?

R 创建一个列的副本,其中新列偏移了某个固定数量

python - 用numpy计算距离矩阵

r - R-自定义直方图中的X轴值

javascript - Chart.js : How to fill the area under the line to a certain point?

Python:如何为具有不同颜色强度或不同圆半径的坐标绘制热图?

在 Shiny 中重复无功输出

r - 相关矩阵 - tidyrgather v.reshape2melt

c++ - __m256d TRANSPOSE4 等效?

r - 识别矩阵中的重复岛并更改它们的值