简体   繁体   English

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

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

A colored 2D matrix plot was created using the following codes:使用以下代码创建彩色二维矩阵图:

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"))

However, this function can only show the numerical values within each cell, but what I want is some pre-specified texts (which can be provided from another data frame) added in each cell, like the screenshot below:但是,这个函数只能显示每个单元格内的数值,但我想要的是在每个单元格中添加一些预先指定的文本(可以从另一个数据框提供),如下面的屏幕截图:

在此处输入图片说明

Is there a way in plotrix or some other R packages (eg ggplot2 ) that can make it?plotrix或其他一些 R 包(例如ggplot2 )中有没有办法做到这一点? Thanks.谢谢。

Here is a way using 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)

在此处输入图片说明

*Note: It isn't necessary to convert to a matrix; *注意:不需要转换为矩阵; it is just a preference.这只是一种偏好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM