You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将包含source、target、count的dataframe转换为类相关矩阵并可视化?

将配对计数数据转换为对称矩阵并绘制热图

步骤1:生成对称矩阵

从原始数据中提取所有唯一组别,创建空矩阵并对称填充计数:

# 提取所有唯一组别并排序
groups <- unique(c(dat$source, dat$target))
groups <- sort(groups)

# 创建空的对称矩阵
mat <- matrix(0, nrow = length(groups), ncol = length(groups),
              dimnames = list(groups, groups))

# 填充矩阵(对称赋值)
for (i in 1:nrow(dat)) {
  src <- dat$source[i]
  tgt <- dat$target[i]
  mat[src, tgt] <- dat$count[i]
  mat[tgt, src] <- dat$count[i]
}

运行后得到的对称矩阵如下:

> mat
   A B C D
A  0 4 5 6
B  4 0 3 3
C  5 3 0 5
D  6 3 5 0

步骤2:绘制热图

提供两种常用的绘制方法:

方法一:用pheatmap快速绘制

# 安装依赖包(首次使用时执行)
# install.packages("pheatmap")
library(pheatmap)

pheatmap(mat,
         display_numbers = TRUE,  # 显示单元格内的计数
         cluster_rows = FALSE,    # 关闭行聚类
         cluster_cols = FALSE,    # 关闭列聚类
         main = "配对计数矩阵热图",
         color = colorRampPalette(c("white", "#2ecc71"))(100))

方法二:用ggplot2自定义绘制

# 安装依赖包(首次使用时执行)
# install.packages(c("ggplot2", "reshape2"))
library(ggplot2)
library(reshape2)

# 将矩阵转换为长格式
mat_melted <- melt(mat)
colnames(mat_melted) <- c("来源", "目标", "计数")

ggplot(mat_melted, aes(x = 来源, y = 目标, fill = 计数)) +
  geom_tile(color = "white") +  # 绘制单元格
  geom_text(aes(label = 计数), color = "black") +  # 添加数值标签
  scale_fill_gradient(low = "white", high = "#2ecc71") +  # 设置填充色渐变
  labs(title = "配对计数矩阵热图", x = "", y = "") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # 调整x轴标签角度

内容的提问来源于stack exchange,提问作者Koundy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 02:52:22