【问题标题】:pivot table in proper order for the heatmap为热图按正确顺序排列的数据透视表
【发布时间】:2021-12-26 07:06:46
【问题描述】:

在创建热图时,我有以下语法:

import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
data=df.rename(columns={0:'Year', 1:'Month', 2:'Count'})
data= pd.pivot_table(data, values='Count', index='Year', columns='Month')
f, ax = plt.subplots(figsize=(15, 6))
sns.heatmap(data, annot=True, fmt="d", linewidths=.5, ax=ax)

并生成以下热图:

我想要的是沿 x 轴升序或降序的月份。即一月、二月、三月等。我如何像this一样完成?

此处的示例数据:

    0        1      2
0   2005    Jan     84482
1   2011    Apr     28243
2   2007    Apr     64992
3   2013    Feb     46542
4   2016    Sept    24445
5   2011    July    23346
6   2019    Dec     28251
7   2015    Jan     34505
8   2007    June    72561
9   2015    Apr     26973
10  2006    May     102896
11  2006    Jan     88664
12  2012    Nov     32046
13  2005    Sept    65498
14  2014    Sept    24856

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:

    如果您的数据框已排序:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    dates = pd.date_range("2000-01-01", periods=48, freq="M")
    df = pd.DataFrame({"Year":dates.year,
                       "Month":dates.month_name().str.slice(stop=3),
                      "Count":np.random.randint(0,100,48)})
    
        Year    Month   Count
    0   2000    Jan 96
    1   2000    Feb 5
    2   2000    Mar 97
    3   2000    Apr 40
    4   2000    May 55
    5   2000    Jun 16
    

    然后:

    df['Month'] = pd.Categorical(df['Month'],categories=df['Month'].unique())
    

    否则创建一个订单列表:

    month_order = pd.date_range("2000-01-01", periods=12, freq="M").month_name().str.slice(stop=3)
    df['Month'] = pd.Categorical(df['Month'],categories=month_order)
    

    情节会奏效:

    data= pd.pivot_table(df, values='Count', index='Year', columns='Month')
    f, ax = plt.subplots(figsize=(15, 6))
    sns.heatmap(data, annot=True, fmt="d", linewidths=.5, ax=ax)
    

    【讨论】:

    • 导入时出现排序问题。一定要喜欢熊猫。
    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    相关资源
    最近更新 更多