R语言ggplot2画四方形的热图展示相关系数的简单小例子
2020-12-19 本文已影响0人
小明的数据分析笔记本
R语言里画热图通常会使用
pheatmap
这个包。如果想使用ggplot2
这个包画热图的话需要借助geom_tile()
这个函数。今天的内容就以相关系数的数据为例介绍一下ggplot2
画热图的一个简单小例子。
第一步是做相关性分析,获得相关系数
R语言里做相关性分析需要准备的数据格式如下:每行是一个样本,每列是一个变量,存储到excel中,然后另存为csv格式数据

需要示例数据的可以直接在文末留言
首先是读入数据
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))

更改配色
ggplot(plotdf,aes(x=Var1,y=Var2))+
geom_tile(aes(fill=value))+
scale_fill_gradient2(low="green",mid="white",high = "red")

将相关系数的数值作为文字标签
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))

相关系数的小数位数太多,我们只保留两位
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))

这样最基本的热图就做好了,接下来是简单的美化
包括去掉灰色背景,去掉坐标轴的标题和小短线
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())

欢迎大家关注我的公众号
小明的数据分析笔记本