为 R 中的 2D 矩阵图的每个单元格添加文本plotrix 和/或 ggplot2

问题描述

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

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

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

enter image description here

plotrix 或其他一些 R 包(例如 ggplot2)中有没有办法做到这一点?谢谢。

解决方法

这是一种使用 ggplot2 的方法。

library(reshape2)
library(ggplot2)

testdf = data.frame(x = c(0,1,1),y = c(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)

enter image description here

*注意:不需要转换成矩阵;这只是一种偏好。