绘制随机化布局并填充文本

jon*_*jon 2 plot r

我试图在R /图形中绘制随机化布局.

Trt <- c(paste ("Trt#", 1:10, sep = ""))
    mydes <- data.frame (block1= sample(Trt), block2 = sample(Trt), block3= sample(Trt), block4= sample( Trt), block5= sample(Trt))
    plot(c(0, NCOL(mydes)), c(0, NROW(mydes)), type= "n", xlab="blocks", ylab = "range")
    grid(lty = 2, col = 1)

    mydes 
       block1 block2 block3 block4 block5
    1  Trt#10  Trt#5  Trt#4  Trt#6  Trt#8
    2   Trt#6  Trt#8  Trt#9  Trt#2  Trt#3
    3   Trt#3  Trt#6  Trt#5 Trt#10  Trt#9
    4   Trt#9  Trt#4  Trt#1  Trt#5  Trt#2
    5   Trt#5  Trt#9  Trt#7  Trt#3  Trt#5
    6   Trt#7  Trt#3  Trt#3  Trt#7  Trt#7
    7   Trt#8 Trt#10  Trt#8  Trt#4  Trt#4
    8   Trt#1  Trt#7 Trt#10  Trt#9  Trt#1
    9   Trt#4  Trt#1  Trt#2  Trt#1 Trt#10
    10  Trt#2  Trt#2  Trt#6  Trt#8  Trt#6
Run Code Online (Sandbox Code Playgroud)

我想在每个网格矩形的中间添加文本.我知道我可以通过添加文本和逐个指定坐标来做到这一点.但是我想要一个带有一些简短循环的通用解决方案,它也可以应用于任何其他维度.

谢谢;

And*_*rie 5

这是一种方法ggplot:

library(ggplot2)

blocks <- expand.grid(
  x = 1:ncol(mydes),
  y = 1:nrow(mydes)
)

blocks$label <- unname(rapply(mydes, as.character))

ggplot(blocks) + 
  geom_rect(aes(xmin=x-0.4, xmax=x+0.4, ymin=y-0.4, ymax=y+0.4), fill="cyan") +
  geom_text(aes(label=label, x=x, y=y)) +
  xlab("Blocks") + ylab("Treatments")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

由于您想绘制此图,而不是仅仅打印一个表,您也可以使用颜色标度来映射具有相同值的处理:

ggplot(blocks) + 
  geom_rect(aes(xmin=x-0.4, xmax=x+0.4, ymin=y-0.4, ymax=y+0.4, fill=label)) +
  geom_text(aes(label=label, x=x, y=y)) +
  xlab("Blocks") + ylab("Treatments") +
  scale_fill_hue("Treatment", h=c(90, 150))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述