Search code examples
pythonmatplotlibdatetimeseabornxticks

x axis tick labels are one position ahead of data points


I have a seaborn lineplot that shows two categories' quarterly count changes. The issue is that the x-axis labels are one position ahead of the data points. I adjusted my code, but it didn't help.

Create example data

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

categories = ['A', 'B']
quarters = []
for year in range(2014, 2024):
    for quarter in range(1, 5):
        quarters.append(f"{year}-Q{quarter}")
data = []
for category in categories:
    for quarter in quarters:
        count = random.randint(40000, 500000)
        data.append({'category': category, 'quarter': quarter, 'count': count})
df = pd.DataFrame(data)

Create the chart

# Create the lineplot
plt.figure(figsize=(10, 6))
ax = sns.lineplot(x="quarter", y="count", hue="category", data=df, marker="o")
plt.xlabel("Quarter")
plt.ylabel("Count")
plt.xticks(rotation=45)

# Set the x-axis tick positions and labels based on the quarters in the DataFrame
x_positions = range(len(quarters))
ax.set_xticks(x_positions)
ax.set_xticklabels(quarters, rotation=45)  # Display every label

plt.tight_layout()
plt.show()

The chart enter image description here


Solution

  • You might be happier with the results you get using

    ax.set_xticklabels(quarters, rotation=45, fontdict={'horizontalalignment': 'right'})
    

    Which looks like this:

    plot with rotated labels and right alignment

    In my opinion it pushes the labels a little too far left, though. The result with rotation=90 is clearer.