SCI图片复现:复杂热图+连接线

复杂热图+连接线

使用patchworkggplotify库将两个热图和基因连线图进行拼接。layout变量定义了每个子图的位置。最后,使用print()函数显示最终图形,使用ggsave()函数将图形保存为PDF文件。

# 加载所需的包
library(ggplot2)
library(ComplexHeatmap)
library(ggforce)
library(circlize)

# 构建示例数据
set.seed(42) # 保证示例数据的一致性
LU_matrix <- matrix(runif(70, 0, 0.5), nrow = 10, ncol = 7)
RD_matrix <- matrix(runif(105, -0.5, 0), nrow = 15, ncol = 7)
RU_matrix <- matrix(runif(30, -0.5, 0), nrow = 10, ncol = 3)
LD_matrix <- matrix(runif(45, 0, 0.5), nrow = 15, ncol = 3)

data <- rbind(cbind(LU_matrix, RU_matrix), cbind(RD_matrix, LD_matrix))
rownames(data) <- paste0("Gene", 1:nrow(data))
colnames(data) <- paste0("Sample", 1:ncol(data))

# 显示前几行数据
head(data)

# 设置颜色映射函数
col_fun <- colorRamp2(c(-0.5, 0, 0.5), c("#04a3ff", "#ffffff", "#ff349c"))

# 构建热图函数
build_heatmap <- function(data, rotate_column_names = FALSE, row_names_side = "right") {
  Heatmap(data,
          col = col_fun,
          rect_gp = gpar(col = "white", lwd = 1),
          cluster_columns = FALSE,
          cluster_rows = FALSE,
          column_names_rot = ifelse(rotate_column_names, 45, -45),
          cell_fun = function(j, i, x, y, width, height, fill) {
            grid.text(sprintf("%.2f", data[i, j]), x, y, gp = gpar(fontsize = 5))},
          show_heatmap_legend = FALSE,
          row_names_side = row_names_side)
}

# 构建两个热图
p1 <- build_heatmap(data)
p2 <- build_heatmap(data, rotate_column_names = TRUE, row_names_side = "left")

# 构建基因连线数据
lines <- data.frame(
  x = as.character(c(rep(1, 25), rep(2, 25))),
  y = c(sample(1:25), sample(1:25)),
  group = rep(1:25, 2)
)

# 构建基因连线图
p3 <- ggplot(lines) +
  geom_link2(aes(x = x, y = y, group = group, colour = stat(index)), size = 2) +
  scale_colour_gradient2(low = "#04a3ff", mid = "#ffffff", high = "#ff349c", midpoint = 0.5) +
  geom_point(aes(x, y, group = group, fill = x), shape = 21, color = "#fc1e1e", size = 4) +
  scale_fill_manual(values = c("#04a3ff", "#ff349c")) +
  theme_minimal() +
  theme(legend.position = "none",
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.border = element_blank(),
        panel.grid = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_blank(),
        plot.title = element_text(size = 0, face = "bold"))

# 拼接热图和基因连线图
library(patchwork)
library(ggplotify)

layout <- c(
  area(t = 1, l = 1, b = 6, r = 3),
  area(t = 1, l = 3, b = 6, r = 7),
  area(t = 1, l = 7, b = 6, r = 9)
)

final_plot <- as.ggplot(p1) + p3 + as.ggplot(p2) + plot_layout(design = layout)

# 显示最终图形
print(final_plot)

# 保存为PDF文件
ggsave("heatmap.pdf", plot = final_plot, height = 8, width = 12)

 

阅读剩余
THE END