gannu
gannu

Reputation: 109

how to prevent seaborn to skip year in xtick label in Timeseries Plot

I have included the screenshot of the plot. Is there a way to prevent seaborn from skipping the xtick labels in timeseries data.

Timeseries plot skipping the years in x axis.

Upvotes: 1

Views: 1414

Answers (2)

Victor Luu
Victor Luu

Reputation: 244

Agree with answer of @steven, just want to say that methods for xticks like plt.xticks or ax.xaxis.set_ticks seem more natural to me. Full details can be found here.

Upvotes: 0

steven
steven

Reputation: 2519

Most seaborn functions return a matplotlib object, so you can control the number of major ticks displayed via matplotlib. By default, matplotlib will auto-scale, which is why it hides some year labels, you can try to set the MaxNLocator.

Consider the following example:

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

# load data
df = sns.load_dataset('flights')
df.drop_duplicates('year', inplace=True)
df.year = df.year.astype('str')

# plot
fig, ax = plt.subplots(figsize=(5, 2))
sns.lineplot(x='year', y='passengers', data=df, ax=ax)
ax.xaxis.set_major_locator(plt.MaxNLocator(5))

This gives you:

enter image description here

ax.xaxis.set_major_locator(plt.MaxNLocator(10))

will give you

enter image description here

Upvotes: 2

Related Questions