0

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)
''
jpf
  • 1,447
  • 12
  • 22
Georg Heiler
  • 16,916
  • 36
  • 162
  • 292
  • I'm not sure . but does this answer your question? https://stackoverflow.com/questions/14852821/aligning-rotated-xticklabels-with-their-respective-xticks – Ehsan May 12 '20 at 21:58

1 Answers1

2

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

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • But they are still jumping around. Now on the other side. Is it possible to simply use 2 characters? – Georg Heiler May 13 '20 at 03:55
  • 1
    Another option is using a monospaced font. Having only two characters won't change that a 'W' is wider in the usual proportional fonts. – JohanC May 13 '20 at 08:49
  • Indeed. But the look of the monospaced font also doesn't make me really happy. Do you know if justification (just like in MS Word) would work for the axis? – Georg Heiler May 13 '20 at 08:50
  • As far as I know, matplotlib text doesn't support such an option. The most advanced text options are in `plt.annotate` which also doesn't seem to consider such type of alignment. – JohanC May 13 '20 at 08:59