This repository has been archived on 2025-01-13. You can view files and clone it, but cannot push or open issues or pull requests.
CircosHeatmap-R/heatmap_script.R

84 lines
2.4 KiB
R
Raw Normal View History

# 加载所需的包
2025-01-11 22:35:13 +08:00
suppressPackageStartupMessages(library(circlize))
suppressPackageStartupMessages(library(RColorBrewer))
2025-01-12 06:00:42 +08:00
suppressPackageStartupMessages(library(ComplexHeatmap))
2025-01-11 22:35:13 +08:00
suppressPackageStartupMessages(library(dendextend))
# 从命令行获取参数
args <- commandArgs(trailingOnly = TRUE)
# 检查参数数量
if (length(args) != 2) {
stop("请提供两个参数输入CSV文件路径和输出PDF文件路径。", call. = FALSE)
}
# 获取输入CSV文件路径和输出PDF文件路径
input_csv <- args[1]
output_pdf <- args[2]
# 检查输入文件是否存在
if (!file.exists(input_csv)) {
2025-01-12 06:00:42 +08:00
stop("输入文件不存在。请检查文件路径。", call. = FALSE)
}
2025-01-12 06:00:42 +08:00
# 函数加载和预处理数据
load_and_preprocess_data <- function(file_path) {
data <- read.table(file = file_path, header = TRUE, row.names = 1, sep = ',')
data_matrix <- as.matrix(data)
normalized_data <- t(scale(t(data_matrix)))
normalized_data[is.na(normalized_data)] <- 0
return(normalized_data)
}
2025-01-12 06:00:42 +08:00
# 加载和预处理数据
cir1 <- load_and_preprocess_data(input_csv)
2025-01-12 06:00:42 +08:00
# 打印数据维度和头部
print(dim(cir1))
print(head(cir1))
2025-01-12 06:00:42 +08:00
# 定义颜色梯度
mycol <- colorRamp2(c(-2.5, 0.3, 3.1), c("blue", "white", "red"))
2025-01-12 06:00:42 +08:00
# 打开PDF设备设置宽度和高度相等
pdf(output_pdf, width = 8, height = 8)
2025-01-12 06:00:42 +08:00
# 设置绘图参数
circos.par(gap.after = c(30))
2025-01-12 06:00:42 +08:00
# 绘制调整后的圆形热图
circos.heatmap(cir1,
col = mycol,
dend.side = "inside",
rownames.side = "outside",
rownames.col = "black",
rownames.cex = 1.3,
track.height = 0.35, # 增加轨道高度
cluster = TRUE,
dend.track.height = 0.18,
dend.callback = function(dend, m, si) {
color_branches(dend, k = 15, col = 1:15)
})
# 添加列名
circos.track(track.index = get.current.track.index(), panel.fun = function(x, y) {
if (CELL_META$sector.numeric.index == 1) {
cn <- colnames(cir1)
n <- length(cn)
2025-01-12 06:00:42 +08:00
circos.text(rep(CELL_META$cell.xlim[2], n) + convert_x(0.5, "mm"),
1:n + 2.5,
cn, cex = 0.6, adj = c(0, 0.5), facing = "inside")
}
}, bg.border = NA)
2025-01-12 06:00:42 +08:00
# 添加图例
lg <- Legend(title = "Exp", col_fun = mycol, direction = "vertical")
grid.draw(lg)
# 清除圆形图
circos.clear()
# 关闭PDF设备
dev.off()
2025-01-12 06:00:42 +08:00
message("热图已成功保存至: ", output_pdf)