Search code examples
pythonmatplotlibseaborndate-format

seaborn x label date format align day of week abbreviation


How can I align the day of week abbreviations to be on the same level? Currently, it is alternating.

ta-

import pandas as pd
import seaborn as sns; sns.set()

df = pd.DataFrame({'dt':['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04'], 'foo':[10, 15, 8, 13]})
df['dt'] = pd.to_datetime(df['dt'])
display(df)

ax = sns.lineplot(x='dt', y='foo', data=df)

import matplotlib.dates as mdates
date_form = DateFormatter("%a %d-%m")
ax.xaxis.set_major_formatter(date_form)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
plt.xticks(rotation=90, horizontalalignment='center', fontsize=28)
''

Solution

  • The simplest way to align the start of the tick labels would be to rotate the other way around:

    plt.xticks(rotation=-90, ha='center', fontsize=28)
    

    rotated clockwise

    Alternatively, the tick labels can be vertically aligned to the bottom, but then they need to be shifted down. The exact distance depends on font, fontsize and text length:

    plt.xticks(rotation=90, ha='center', va='bottom', fontsize=28)
    plt.tick_params(axis='x', which='major', pad=150)
    

    rotated anti clockwise

    Still another option is to choose a monospace font. Note that with a usual font, a 'W' takes up much more space than an 'i'. If such a monospace font is desired, "courier new" is one of best-looking options.

    plt.xticks(rotation=90, horizontalalignment='center', fontsize=28, family=['courier new', 'monospace'])
    

    monospace font