seaborn.heatmap()的參數
seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annot_kws=None, linewidths=0, linecolor='white', cbar=True, cbar_kws=None, cbar_ax=None, square=False, xticklabels='auto', yticklabels='auto', mask=None, ax=None, **kwargs)
⚪ 繪制熱圖
uniform_data = np.random.rand(10,12) #隨機創建10行12列的數組 pd.DataFrame(uniform_data) #以一個數據框的格式來顯示 f,ax = plt.subplots(figsize=(9,6)) #定義一個子圖寬高為9和6 ax存儲的是圖形放在哪個位置 ax = sns.heatmap(uniform_data,vmin = 0,vmax = 1) #vmin,vmax定義了色彩圖的上下界 # sns.heatmap(uniform_data) #此語句會默認圖形的大小畫熱圖
⚪ 使用發散色圖繪制以0為中心得數據的熱力圖
uniform_data = np.random.randn(10, 12) f, ax = plt.subplots(figsize=(9, 6)) ax = sns.heatmap(uniform_data, center=0) #參數center = 0
⚪ 以數據集 flights 為例繪圖
flights = pd.read_csv('C:\\Users\\86130\\Desktop\\flights.csv')
flights = sns.load_dataset("flights") 因為XJ的網絡鏈接不了github所以該語句不可用
網址https://github.com/mwaskom/seaborn-data直接下載數據集 👆
數據集 flights 的部分截圖:
高效的函數pivot(),該函數有三個參數(index,columns,values),第一個參數index是指新表的索引,第二個參數columns是新表的列名,第三個參數values是指新表中的值,看效果就比較明確了 👇
new_flights = flights.pivot("month","year","passengers")
new_flights的數據顯示:
f,ax = plt.subplots(figsize=(9,6)) sns.heatmap(new_flights)
f,ax = plt.subplots(figsize=(12,9)) sns.heatmap(new_flights,annot = True,fmt = "d",linewidth =0.5,cmap = 'Blues',xticklabels = 2,yticklabels = False,cbar = False) #annot=True 為每個單元格寫入值。 #參數fmt是指添加值的格式。這里設置為整數型 #linewidth是指划分每個單元格的行的寬度 #cmap設置熱圖的顏色 #xticklabels與yticklabes默認為1,即標簽沒有中斷,若設置為False則不顯示標簽, #參數cbar默認為True,即繪制顏色條
⚪ 使用不同的軸作為顏色條,直接用代碼吧。
grid_kws = {"height_ratios": (.9, .05), "hspace": .3} f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws) ax = sns.heatmap(new_flights, ax=ax, cbar_ax=cbar_ax, cbar_kws={"orientation": "horizontal"})
subplots函數中的參數gridspec_kw是將字典的關鍵字傳遞給GridSpec構造函數創建子圖放在網格里。heatmap函數中的參數ax指繪制圖的軸,否則使用當前活動的軸,cbar_ax用於繪制顏色條的軸,否則從主軸獲取;cbar_kwsfig.colorbar的關鍵字參數.這部分不太會用大白話解釋,直接上圖吧 👆
⚪ 繪制相關系數矩陣,因為對稱僅繪制一半
corr = np.corrcoef(np.random.randn(10, 200)) mask = np.zeros_like(corr) print(mask) mask[np.triu_indices_from(mask)] = True #把上部分設置為1 #設置為1 的單元格將不再顯示 #mask[np.tril_indices_from(mask)] = True #把下部分設置為1 print(mask) with sns.axes_style("white"): ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True)
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] [[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [0. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1. 1. 1. 1. 1.] [0. 0. 0. 1. 1. 1. 1. 1. 1. 1.] [0. 0. 0. 0. 1. 1. 1. 1. 1. 1.] [0. 0. 0. 0. 0. 1. 1. 1. 1. 1.] [0. 0. 0. 0. 0. 0. 1. 1. 1. 1.] [0. 0. 0. 0. 0. 0. 0. 1. 1. 1.] [0. 0. 0. 0. 0. 0. 0. 0. 1. 1.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]