Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort my x-axis by ascending month order?

So I have a dataframe with the indices as datetime objects. Image1 I have created a new column to indicate which month each 'ride' in the dataframe is in:

import numpy as np
import datetime as dt
from datetime import datetime    
months = df.index.to_series().apply(lambda x:dt.datetime.strftime(x, '%b %Y')).tolist()
df['months'] = months
df1 = df[['distance','months']]

Which gives:

image2

When I try to plot it onto a line graph using seaborn using months as the x-axis, it sorts it in alphabetical order, starting with april then august, etc.

l = sns.lineplot(x='months',y='distance',data=df1)
plt.xticks(rotation=45)

image3

I don't really understand why it does this as in the dataframe that I use, the months are sorted in ascending order according to their months. Is there a way I can make it so my x-axis starts with Jan2018 and ends in July2019?

like image 212
Daichi Avatar asked Dec 12 '25 15:12

Daichi


1 Answers

The x-coordinates must be numeric. When you supply an array of strings, Seaborn automatically sort it alphabetically. What you want can be achieved with sort=False (the default is True):

# True or omitted
sns.lineplot(x='month', y='distance', data=df1, sort=True)

Sort = True

# Set to False to keep the original order in your DataFrame
sns.lineplot(x='month', y='distance', data=df1, sort=False)

Sort = False

like image 116
Code Different Avatar answered Dec 15 '25 08:12

Code Different