PV8
PV8

Reputation: 6270

Order the x axis in seaborn for two columns

I wanna plot a dataframe with seaborn lineplot, which has the following structure:

A  Year Month diff
Der 2019 1    3
Der 2019 2    4
Die 2019 1    1
Die 2019 2    1

Right now I am trying:

sns.lineplot(x= ['Year', 'Month'], y='diff', hue='A', ci=None, data = df)
plt.show()

How can I get a timeline graph starting with 2019 1 and going over the order of the months without having a time column?

Upvotes: 1

Views: 654

Answers (1)

jhansen
jhansen

Reputation: 1136

You could create a new date column from the year and month and just set the day to be 1:

from datetime import date
import matplotlib.dates as mdates

df['date'] = df.apply(lambda row: date(row['Year'], row['Month'], 1), axis=1)
ax = sns.lineplot(x='date', y='diff', hue='A', ci=None, data=df)

# To only show x-axis ticks once per month:
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))

Upvotes: 1

Related Questions