Python – Adding a custom tick and label

matplotlibpython

I would like to add a custom major tick and label in matplotlib. A typical use is to add a label at the location math.pi with the label "$\pi$". My aim is to leave the other ticks as is: I would like to retain the original major and minor ticks with the formatting that have been previously chosen but with this extra tick and label. I have figured out a way (and found posts on these forums) to add the tick:

list_loc=list(ax.xaxis.get_majorticklocs())
list_loc.append(pos)
list_loc.sort()
ax.xaxis.set_ticks(list_loc)

My trouble is with the label. I have tried to retrieve the labels in a similar way with ax.xaxis.get_majorticklabels() but that gives me a list of matplotlib.text.Textwhich I am unsure how to deal with. My intention was to get the list of labels as strings, to add the new label (at the correct position) and then use ax.xaxis.set_ticklabels(list_label) in a way that is similar to the location.

Best Answer

This is what I usually do, though I've never been completely satisfied with the approach. There may be a better way, without calling draw().

fig,ax=plt.subplots()
x=linspace(0,10,1000)
x.plot(x,exp(-(x-pi)**2))
plt.draw() # this is required, or the ticklabels may not exist (yet) at the next step
labels = [w.get_text() for w in ax.get_xticklabels()]
locs=list(ax.get_xticks())
labels+=[r'$\pi$']
locs+=[pi]
ax.set_xticklabels(labels)
ax.set_xticks(locs)
ax.grid()
plt.draw()

enter image description here