30

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
  • 36,675
  • 19
  • 86
  • 83
Vinay
  • 1,149
  • 3
  • 16
  • 28

2 Answers2

41

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
  • 37,862
  • 7
  • 57
  • 71
24

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
  • 36,675
  • 19
  • 86
  • 83