r语言相关性热图ggplot
时间: 2025-01-15 22:50:07 浏览: 87
### 使用 R 语言 ggplot2 绘制相关性热图
为了创建一个带有 P 值的相关性热图,可以利用 `ggplot2` 和其他辅助包来完成数据处理和绘图工作。下面展示了一个完整的流程,包括计算相关系数矩阵及其对应的 p 值,并最终通过 `ggplot2` 来呈现这些信息。
#### 安装必要的软件包
如果尚未安装所需的库,则可以通过以下命令进行安装:
```r
install.packages(c("ggplot2", "reshape2", "corrplot"))
```
#### 加载所需库并准备数据集
加载必需的 R 库,并定义用于生成随机数的数据框作为例子:
```r
library(ggplot2)
library(reshape2)
set.seed(123) # 设置种子以便重现结果
data <- as.data.frame(matrix(rnorm(90), ncol=9))
names(data) <- paste0('Var', 1:ncol(data)) # 自定义列名
head(data)
```
#### 计算皮尔逊相关性和p值
编写函数以返回两个向量之间的 Pearson 相关系数及相应的显著性水平 (p-value),并将此应用于整个数据集中每一对变量之间:
```r
cor_with_pvalue <- function(x, y){
test_result <- cor.test(x,y)
return(c(test_result$estimate,test_result$p.value))
}
cors_and_ps <- outer(
colnames(data),
colnames(data),
Vectorize(function(i,j){cor_with_pvalue(data[,i], data[,j])})
)
dim(cors_and_ps)<-c(ncol(data)*2, ncol(data))
cors_matrix<-matrix(unlist(cors_and_ps)[seq(1,length(unlist(cors_and_ps)),by=2)],nrow=nrow(data))
ps_matrix<-matrix(unlist(cors_and_ps)[-seq(1,length(unlist(cors_and_ps)),by=2)],nrow=nrow(data))
rownames(cors_matrix)=colnames(data); rownames(ps_matrix)=colnames(data);
colnames(cors_matrix)=colnames(data); colnames(ps_matrix)=colnames(data);
# 将P值转换为星号表示法
stars <- matrix(ifelse(ps_matrix<0.001,'***',
ifelse(ps_matrix<0.01,'** ',
ifelse(ps_matrix<0.05,'* ',' '))),
dimnames=list(NULL,colnames(data)))
```
#### 创建热力图
现在有了相关性的数值以及它们各自的统计意义标记之后,就可以构建美观易读的相关性热图了:
```r
melted_cors <- melt(cors_matrix,"Variable_1","Variable_2","Correlation")
ggplot(melted_cors,aes(Variable_1, Variable_2, fill=Correlation,label=round(Correlation,digits=2))) +
geom_tile(color="white")+
scale_fill_gradient2(low="blue", high="red", mid="white",
midpoint=mean(abs(cors_matrix)),
limit=c(-1,1), space="Lab", name="Pearson\nCorrelation")+
theme_minimal()+
coord_fixed()+
labs(title='Heatmap of Correlations with Significance Levels')+
geom_text(aes(label=paste(round(Correlation, digits=2)," ", stars[as.numeric(Variable_1),as.numeric(Variable_2)])), size=3)+
theme(axis.text.x = element_text(angle=-45,hjust=.7,vjust=0.5))
```
上述代码片段展示了如何使用 `ggplot2` 结合自定义的颜色渐变方案、文本标签以及其他美化选项来制作一张既直观又富含信息量的相关性热图[^1]。
阅读全文
相关推荐


















