为 R 中二维矩阵图的每个单元格添加文本 (plotrix and/or ggplot2)

add text for each cell of a 2D matrix plot in R (plotrix and/or ggplot2)

使用以下代码创建了彩色二维矩阵图:

library(plotrix)
testdf = data.frame(c(0,1,1),c(1,1,2),c(1,2,2))
color2D.matplot(testdf, 
                show.values = FALSE,
                axes = FALSE,
                xlab = "",
                ylab = "",
                vcex = 2,
                vcol = "black",
                extremes = c("red", "yellow", "green"))

然而,这个函数只能显示每个单元格内的数值,但我想要的是在每个单元格中添加一些预先指定的文本(可以从另一个数据框提供),如下面的截图:

plotrix 或其他一些 R 包(例如 ggplot2)是否有方法可以做到?谢谢。

这是使用 ggplot2 的方法。

library(reshape2)
library(ggplot2)

testdf = data.frame(x = c(0,1,1),y = c(1,1,2),z = c(1,2,2))

# Convert testdf dataframe to a matrix.
df <- as.matrix(testdf)
# Flip the matrix horizontally, and put into long format.
df<-df[c(3:1), ,drop = FALSE] %>% 
  melt()

# Create a new dataframe with the names for each tile.
testdf_names <- data.frame(x = c("A","C","B"),y = c("AB","CD","C"),z = c("B","E","D"))
#Then, do the same process as above by first putting into a matrix.
df_names <- as.matrix(testdf_names)
# Flip the matrix horizontally, and put into long format.
df_names<-df_names[c(3:1), ,drop = FALSE] %>% 
  melt() %>% 
  dplyr::rename(names = value)

# Join the dataframes together for plotting.
df_new <- df %>% 
  dplyr::group_by(Var1, Var2) %>% 
  dplyr::left_join(df_names)

# Plot.
ggplot(df_new, aes(x = Var2, y = Var1)) + 
  geom_tile(aes(fill=as.factor(value)), color = "black", size = 1) + 
  scale_fill_manual(values=c("red", "yellow", "green")) +
  theme_void() + 
  theme(legend.position="none") +
  geom_text(aes(label=names), size = 30)

*注:不需要转为矩阵;这只是一个偏好。