while creating a heatmap I have following syntax:
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)
and that generates following heatmap:

What I want is ascending or descending order of month along x-axis. That is Jan, Feb, Mar, etc. How do I accomplish like this?
Sample data here:
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
If your data frame is sorted:
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
Then:
df['Month'] = pd.Categorical(df['Month'],categories=df['Month'].unique())
Else create one list of the order:
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)
And the plot will work:
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)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With