pivot table 以热图的正确顺序
pivot table in proper order for the heatmap
在创建热图时我有以下语法:
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
如果您的数据框已排序:
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)
在创建热图时我有以下语法:
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
如果您的数据框已排序:
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)