sns.heatmap y 轴未被覆盖

sns.heatmap y axis not being overwritten

目标:我想从具有 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 轴仅显示 'Hour' 索引或完全覆盖它并在 y 轴上设置值 0-23。

最简单的解决方法是从数据框中删除不需要的索引(在绘图时)。或者,如果先前 ax 已被赋予正确的值(通过 fig, ax = plt.subplots(...) 或通过 ax = plt.gca()),您可以调用 ax.set_yticklabels(range(0,24), rotation=0)。只有当所有 24 个级别都存在数据框。

请注意,您的代码似乎混合了“新”object-oriented interface 与旧 pyplot 界面。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

N = 2000
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
df = pd.DataFrame({'Hour': np.random.randint(0, 24, N),
                   'Profile_Name': np.random.choice(['Johan', 'Sebastian', 'Stephanie'], N),
                   'Weekday': np.random.choice(weekdays, N),
                   'Value': np.random.randint(1, 4, N)
                   })
df['Weekday'] = pd.Categorical(df['Weekday'], weekdays)  # set a fixed order
heatmap_df = df.pivot_table(values='Value', index=['Hour', 'Profile_Name'], columns=['Weekday'])

Names = heatmap_df.index.get_level_values('Profile_Name').unique()

for Profile in Names:
    fig, ax = plt.subplots(figsize=(15, 10))
    sns.heatmap(heatmap_df[heatmap_df.index.get_level_values('Profile_Name').isin([Profile])].droplevel(1, axis=0),
                annot=True, fmt='g', cmap="Blues", ax=ax)
    ax.set_title(Profile, fontsize=20)
    ax.set_xlabel('Weekday', fontsize=15)  
    ax.set_ylabel('Time', fontsize=15) 
    # ax.set_yticklabels(range(0,24), rotation=0)
    plt.show()