基因与免疫细胞相关性热图代码
时间: 2025-02-08 11:00:49 浏览: 77
### 绘制基因与免疫细胞相关性热图
为了绘制基因表达水平和免疫细胞浸润之间的相关性热图,可以采用Python或R编程语言中的多种方法。以下是具体实现方式:
#### 使用 Python 和 Seaborn 库绘制热图
Seaborn 是基于 Matplotlib 的高级接口,非常适合用于创建统计图形。
```python
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# 创建示例数据框 df_genes 表示基因表达矩阵, df_cells 表示免疫细胞比例矩阵
df_genes = pd.DataFrame({
'Gene1': [0.5, 0.7, 0.6],
'Gene2': [0.8, 0.9, 0.7],
}, index=['Sample1', 'Sample2', 'Sample3'])
df_cells = pd.DataFrame({
'CellTypeA': [0.2, 0.4, 0.3],
'CellTypeB': [0.6, 0.5, 0.7],
}, index=['Sample1', 'Sample2', 'Sample3'])
# 计算两者的皮尔逊相关系数矩阵
correlation_matrix = df_genes.corrwith(df_cells.T)
plt.figure(figsize=(10, 8))
sns.heatmap(correlation_matrix.unstack().dropna().reset_index(), annot=True, fmt='.2f')
plt.title('Correlation between Gene Expression and Immune Cell Infiltration')
plt.show()
```
此代码片段展示了如何计算并可视化基因表达量与不同类型免疫细胞丰度之间关联性的过程[^1]。
#### 利用 R 和 pheatmap 包制作更复杂的热图
对于生物信息学领域而言,R 有着更为丰富的生态资源来处理这类问题。pheatmap 提供了更多的自定义选项以便更好地呈现复杂的数据结构。
```r
library(pheatmap)
library(dplyr)
# 构建模拟数据集
genes <- data.frame(
Sample1 = c(0.5, 0.8),
Sample2 = c(0.7, 0.9),
row.names=c("Gene1", "Gene2"))
cells <- data.frame(
Sample1 = c(0.2, 0.6),
Sample2 = c(0.4, 0.5),
row.names=c("CellTypeA", "CellTypeB"))
combined_data <- t(genes) %*% cells / sqrt(rowSums(t(genes)^2)) * sqrt(colSums(cells^2))
# 调整颜色方案和其他参数以适应需求
pheatmap(combined_data,
color=colorRampPalette(c("#FFEDA0","#FEB24C","#FD8D3C"))(100),
show_rownames=TRUE,
show_colnames=TRUE,
main="Heatmap of Correlations Between Genes and Immune Cells")
```
这段脚本说明了怎样利用线性代数运算得到标准化后的协方差作为衡量标准,并以此为基础构建出美观且易于理解的相关性图表[^2]。
阅读全文
相关推荐


















