19

I am unable to set x axis ticklabels for a seaborn lineplot correctly.

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({'a':np.random.rand(8),'b':np.random.rand(8)})
sns.set(style="darkgrid")
g = sns.lineplot(data=df)
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])

enter image description here

The years on the x axis are not aligning properly.

tdy
  • 26,545
  • 9
  • 43
  • 50
Vinay
  • 944
  • 3
  • 11
  • 23

2 Answers2

28

Whenever you set the x-ticklabels manually, you should try to first set the corresponding ticks, and then specify the labels. In your case, therefore you should do

g = sns.lineplot(data=df)
g.set_xticks(range(len(df))) # <--- set the ticks first
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])

enter image description here

Sheldore
  • 35,129
  • 6
  • 43
  • 58
4

As of matplotlib 3.5.0

set_xticklabels is now discouraged:

The use of this method is discouraged because of the dependency on tick positions. In most cases, you'll want to use set_xticks(positions, labels) instead.

Now set_xticks includes a new labels param to set ticks and labels simultaneously:

ax = sns.lineplot(data=df)
ax.set_xticks(range(len(df)), labels=range(2011, 2019))
#                             ^^^^^^

tdy
  • 26,545
  • 9
  • 43
  • 50