目標:我想從具有 2 個索引的資料幀創建熱圖。第二個索引稱為“Profile_Name”,也用于遍歷資料幀以創建多個熱圖。
問題:sns.heatmap 不允許我更改 y 軸上的值。
重新創建資料框的代碼
df = pd.DataFrame([['Monday', 1, 'Sebastian', 3],
['Monday', 2, 'Sebastian', 6],
['Monday', 3, 'Living room', 10],
['Tuesday', 1,'Sebastian', 6],
['Tuesday', 2,'Sebastian', 3],
['Tuesday', 3,'Sebastian', 8],
['Wednesday', 1,'Sebastian', 6],
['Wednesday', 2,'Sebastian', 3],
['Wednesday', 3,'Sebastian', 9],
['Tuesday', 1,'Living room', 6],
['Monday', 2,'Living room', 10]],
columns=['Weekday', 'Hour', 'Profile_Name', 'Counts'])
heatmap_df = df.pivot_table(index=('Hour', 'Profile_Name') ,columns='Weekday',values='Counts', aggfunc=lambda x:x).fillna(0)
heatmap_df.head()
創建熱圖的代碼
Names = df.Profile_Name.unique()
for Profile in Names:
plt.subplots(figsize=(15,10))
sns.heatmap(heatmap_df[heatmap_df.index.get_level_values('Profile_Name').isin([Profile])], annot= True, fmt='g', cmap="Blues")
plt.title(Profile, fontsize = 20) # title with fontsize 20
plt.xlabel('Weekday', fontsize = 15) # x-axis label with fontsize 15
plt.ylabel('Time', fontsize = 15) # y-axis label with fontsize 15
#ax.set_yticks(range(0,24)) ## doesnt work
plt.show()
熱圖的外觀

如何從 y 軸洗掉第二個索引“Profile_Name”,在螢屏截圖中顯示為“Sebastian”?我希望 y 軸僅顯示“小時”索引或完全覆寫它并在 y 軸上設定值 0-23。
uj5u.com熱心網友回復:
最簡單的解決方法是從資料框中洗掉不需要的索引(在繪圖時)。或者,您可以呼叫ax.set_yticklabels(range(0,24), rotation=0)if 先前ax已被賦予正確的值(通過fig, ax = plt.subplots(...)或通過ax = plt.gca()。只有在資料幀中存在所有 24 個級別時才有效。
請注意,您的代碼似乎將“新”
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350085.html
標籤:Python matplotlib 海生 热图 y轴
下一篇:用回圈生成幾個子圖
