欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用R语言ggplot2快速绘制简易热图:先做相关系数分析,得到相关系数值

最编程 2024-02-10 13:02:29
...

R语言里做相关性分析需要准备的数据格式如下:每行是一个样本,每列是一个变量,存储到excel中,然后另存为csv格式数据

image.png

需要示例数据的可以直接在文末留言

首先是读入数据
df<-read.csv("example_data/cor_plot_example.csv",
             header=T,
             row.names = 1)
df
相关性分析

直接用cor()函数获得相关系数矩阵

cordf<-cor(df)
cordf
相关系数矩阵是宽格式的数据,ggplot2作图通常是长格式数据,把宽格式变成长格式直接使用reshape2包中的melt()函数就可以了
plotdf<-reshape2::melt(cordf)
plotdf
接下来就是用ggplot2画图了

最基本的热图

library(ggplot2)
ggplot(plotdf,aes(x=Var1,y=Var2))+
  geom_tile(aes(fill=value))
image.png
更改配色
ggplot(plotdf,aes(x=Var1,y=Var2))+
  geom_tile(aes(fill=value))+
  scale_fill_gradient2(low="green",mid="white",high = "red")
image.png
将相关系数的数值作为文字标签
ggplot(plotdf,aes(x=Var1,y=Var2))+
  geom_tile(aes(fill=value))+
  scale_fill_gradient2(low="green",mid="white",high = "red")+
  geom_text(aes(label=value))
image.png
相关系数的小数位数太多,我们只保留两位
plotdf$value<-round(plotdf$value,2)
ggplot(plotdf,aes(x=Var1,y=Var2))+
  geom_tile(aes(fill=value))+
  scale_fill_gradient2(low="green",mid="white",high = "red")+
  geom_text(aes(label=value))
image.png
这样最基本的热图就做好了,接下来是简单的美化

包括去掉灰色背景,去掉坐标轴的标题和小短线

ggplot(plotdf,aes(x=Var1,y=Var2))+
  geom_tile(aes(fill=value))+
  scale_fill_gradient2(low="green",mid="white",high = "red")+
  geom_text(aes(label=value))+
  theme(panel.background = element_blank(),
        axis.title = element_blank(),
        axis.ticks = element_blank())
image.png

欢迎大家关注我的公众号

小明的数据分析笔记本