How to place tick label above grid line in matplotlib

Question:

I wanted to place my tick labels just on top of the grid lines of my graph like it shows in the image below.

Image of the graph I want to replicate

I tried setting the direction to ‘in’ and the pad to -22 in tick_params but I don’t know how to move the labels slightly up to achieve what I want.

My code:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# My lists
dates = []
ratings = []

fig = plt.figure()
ax = fig.add_subplot()

fig.set_facecolor('#2f3136')
ax.set_facecolor('#2f3136')
ax.spines['bottom'].set_color('grey')
ax.spines['right'].set_color('grey')
ax.tick_params(axis='x', colors='grey')
ax.tick_params(axis='y', colors='grey',direction='in',pad=-22)
ax.yaxis.tick_right()
ax.spines[['left','top']].set_visible(False)
ax.grid(axis='y')
fig.set_figwidth(10)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.xaxis.set_major_locator(mdates.MonthLocator())

plt.plot(dates, ratings)

And this is what I am getting

The result of my code

Asked By: spl1ce

||

Answers:

Set the yticklabels vertical and horizontal alignments (after plotting) and it should look as expected.

ax.set_yticklabels(ax.get_yticklabels(), ha="right", va="bottom")
ax.tick_params(axis='y', colors='grey', direction='in', pad=-5)

Note that the tick_params(pad) value has been reduced since the text is already right aligned.

enter image description here

Answered By: thmslmr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.