user579383 user579383 - 6 months ago 25
Python Question

Modify a specific x-axis tick label in python

I am an undergrad newbie to the Python pyplot. What I want to do is to plot a function against a sequence, for example,

x = [1,2,3,4,5]

function naturally gives a nice figure. But I want to replace on the x-axis the tick label "2" by a string say "key point" and at the same time make the tick labels, for example, "4" and "5" invisible. How can I achieve this in

Your help will be highly appreciated.


This is how you do it:

from matplotlib import pyplot as plt

x = [1,2,3,4,5]
y = [1,2,0,2,1]

ax = plt.gca() # grab the current axis
ax.set_xticks([1,2,3]) # choose which x locations to have ticks
ax.set_xticklabels([1,"key point",2]) # set the labels to display at those ticks

By omitting 4 and 5 from your xtick list, they won't be shown.