So I have a dataframe with the indices as datetime objects.
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:

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)

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?
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)

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

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