python--seaborn熱力圖

seaborn是專門用于統(tǒng)計(jì)數(shù)據(jù)可視化的包,可媲美R語言中的ggplot2包。本文介紹用seaborn繪制熱力圖。

環(huán)境

  • python3.9
  • win10 64bit
  • seaborn==0.11.1
  • matplotlib==3.3.4
  • pandas==1.2.1

數(shù)據(jù)

熱力圖的一個(gè)常見應(yīng)用場景是繪制相關(guān)系數(shù)熱力圖,數(shù)據(jù)準(zhǔn)備一個(gè)相關(guān)系數(shù)矩陣。

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 80  # 圖形分辨率
pd.options.display.notebook_repr_html=False  # 表格顯示
# 相關(guān)系數(shù)矩陣
np.random.seed(1)  # 隨機(jī)種子
mat=pd.DataFrame(np.random.rand(3,6),columns=list('abcdef')).corr()
mat
          a         b         c         d         e         f
a  1.000000  0.297407 -0.610065 -0.908297 -0.997893 -0.991160
b  0.297407  1.000000 -0.937936  0.129262 -0.234835 -0.421449
c -0.610065 -0.937936  1.000000  0.222660  0.557370  0.709796
d -0.908297  0.129262  0.222660  1.000000  0.933525  0.844767
e -0.997893 -0.234835  0.557370  0.933525  1.000000  0.980463
f -0.991160 -0.421449  0.709796  0.844767  0.980463  1.000000

繪制

調(diào)用heatmap方法繪制熱力圖。

# 熱力圖
sns.heatmap(mat)
plt.show()

heatmap_6_0.png

調(diào)整調(diào)色板

設(shè)置vminvmax參數(shù)可以調(diào)整調(diào)色板的下限值和上限值。

# 設(shè)置調(diào)色板上下限值
sns.heatmap(mat,vmin=0,vmax=1)
plt.show()
heatmap_8_0.png

設(shè)置cmap參數(shù),可以修改調(diào)色板樣式。

# 修改調(diào)色板
sns.heatmap(mat,cmap='YlGnBu')
plt.show()
heatmap_10_0.png

隱藏圖例

設(shè)置參數(shù)cbar=False可以隱藏圖例。

# 隱藏圖例
sns.heatmap(mat,cbar=False)
plt.show()
heatmap_12_0.png

顯示數(shù)值

設(shè)置參數(shù)annot=True可以顯示熱力圖上的具體數(shù)值,設(shè)置fmt參數(shù),可以修改數(shù)值顯示的樣式。

# 顯示數(shù)值熱力圖
sns.heatmap(mat,annot=True,fmt='.3f')
plt.show()
heatmap_14_0.png

更多參考seaborn熱力圖

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容