r - R 中带有非空单元格的绘图板

标签 r graphics

我试着画这样的东西(但非常简单):

enter image description here

所以问题是我设置了 heightwidthnob - 炸弹数量,我想用 绘制表格height*width 单元格,其中将由 nob 随机设置炸弹(它可能是例如文本“炸弹”,这并不重要)。此外,对于每个空单元格,我想计算附近的炸弹数量并将该数字放在该单元格的中间(当为零时 - 什么都没有)。但我真的不知道为此的一些“算法”。我画出合适尺寸的木板,这就是我所能做的。有什么想法吗?

 w <- 7
 h <- 5
 nob <- 5
 plot.new()
 plot.window(xlim=c(0,w), ylim=c(0,h))
 rect(0, 0, w, h)
 for (i in 1:h-1){
    lines(x=c(0,w), y=c(i,i))
 }
 for (j in 1:w-1){
    lines(x=c(j,j), y=c(0, h))
 }
 sample(w*h, nob)

最佳答案

圣诞节的一些有趣的事情:

w <- 7
h <- 5
nob <- 5
nwal <- 7
set.seed(42) #for reproducibility

m <- matrix(0, ncol=w, nrow=h)
#place the walls
m[sample(length(m), nwal)] <- 1

o <- matrix("", ncol=w, nrow=h)
#place the bombs
o[sample(which(m == 0), nob)] <- "o"

#http://stackoverflow.com/a/22573306/1412059
#there is probably an alternative using igraph
sumNeighbors <- function(z) {
  rbind(z[-1,],0) + 
    rbind(0,z[-nrow(z),]) + 
    cbind(z[,-1],0) + 
    cbind(0,z[,-ncol(z)]) +
    cbind(rbind(z[-1,-1],0),0) +
    cbind(0,rbind(z[-1,-ncol(z)],0)) +
    cbind(rbind(0,z[-nrow(z),-1]),0) +
    cbind(0,rbind(0,z[-nrow(z),-ncol(z)]))  
}

library(reshape2)
DF <- melt(m, varnames = c("x", "y"), value.name = "z")
DF <- merge(DF, melt(o, varnames = c("x", "y"), value.name = "b"))
DF <- merge(DF, melt(sumNeighbors(o == "o"), varnames = c("x", "y"), value.name = "n"))

DF$n[DF$n == 0 | DF$b == "o" | DF$z == 1] <- ""
DF$t <- paste0(DF$n, DF$b)

library(ggplot2)
ggplot(DF, aes(x=x, y=y, fill=factor(z))) +
  geom_tile(color="dark grey") +
  geom_text(aes(label=t)) +
  theme(axis.title = element_blank(),
        axis.text = element_blank(), 
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        legend.position = "none")

resulting plot

关于r - R 中带有非空单元格的绘图板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27679157/

相关文章:

R:为什么 group_by 即使在使用 quosures 时仍然需要 "do"

函数默认参数和命名值

qt - 如何更改 QGraphicsTextItem 的背景?

java - 访问 BufferedImage 线程是否安全

Java-重画背景

r - 在 Shiny 中隐藏 sliderInput 的值

r - 提取矩阵列及其名称

r - 如何创建要插入到 ggplot 中的对象(当有多个带 + 的部分时)?

android - 如何制作包含多个部分的单杠?

iphone - 如何存储 CALayers 以便重复使用?