天天看點

python畫熱力圖(相關系數矩陣圖)

reference:https://blog.csdn.net/a19990412/article/details/79304944

用seaborn包畫

plt.subplots(figsize=(9, 9))設定畫面大小,會使得整個畫面等比例放大的

sns.heapmap()這個當然是用來生成熱力圖的啦

df是DataFrame, pandas的這個類還是很常用的啦~

df.corr()就是得到這個dataframe的相關系數矩陣

把這個矩陣直接丢給sns.heapmap中做參數就好啦

sns.heapmap中annot=True,意思是顯式熱力圖上的數值大小。

sns.heapmap中square=True,意思是将圖變成一個正方形,預設是一個矩形

sns.heapmap中cmap="Blues"是一種模式,就是圖顔色配置方案啦,我很喜歡這一款的。

sns.heapmap中vmax是顯示最大值

# -*- coding: UTF-8 -*-
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# a = np.random.rand(4,3)

a = np.array([[1,0.107562,0.270034,0.266753],
              [0.107562,1,0.543716,0.540923],
              [0.270034,0.543716,1,0.950266],
              [0.266753,0.540923,0.950266,1]])

fig, ax = plt.subplots(figsize = (9,9))
#二維的數組的熱力圖,橫軸和數軸的ticklabels要加上去的話,既可以通過将array轉換成有column
#和index的DataFrame直接繪圖生成,也可以後續再加上去。後面加上去的話,更靈活,包括可設定labels大小方向等。
sns.heatmap(pd.DataFrame(np.round(a,2), columns = ['img0', 'img1', 'img2','img3'], index = ['img0', 'img1', 'img2','img3']),
                annot=True, vmax=1,vmin = 0, xticklabels= True, yticklabels= True, square=True, cmap="Blues")
#sns.heatmap(np.round(a,2), annot=True, vmax=1,vmin = 0, xticklabels= True, yticklabels= True,
#            square=True, cmap="YlGnBu")
# ax.set_title('二維數組熱力圖', fontsize = 18)
ax.set_ylabel('image', fontsize = 18)
ax.set_xlabel('iamge', fontsize = 18) #橫變成y軸,跟矩陣原始的布局情況是一樣的
plt.savefig('./out.png')
plt.show()
           
python畫熱力圖(相關系數矩陣圖)