R語言里畫熱圖通常會使用
pheatmap
這個包谒拴。如果想使用ggplot2
這個包畫熱圖的話需要借助geom_tile()
這個函數蜜唾。今天的內容就以相關系數的數據為例介紹一下ggplot2
畫熱圖的一個簡單小例子榜聂。
第一步是做相關性分析,獲得相關系數
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
歡迎大家關注我的公眾號
小明的數據分析筆記本