I'd like to remove all but the first and last tick labels, but keep their ticks on a plot. However, using the below code, all labels get removed
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 1)
ax.plot(np.arange(10))
locs = ax.get_xticks()
labels = ax.get_xticklabels()
labels[1].set_text('') # Should only remove the 2nd label
ax.set_xticks(locs)
ax.set_xticklabels(labels)
results in:
Where are all my labels are removed, rather than just the 2
. How can I remove just that single number?
I'd expect the following plot to show up (rendered by BigBen using the code above in a comment, using matplotlib 3.6.0 and Python 3.9.7):
Preferably in a method capable of removing all but the first and last label. For that I tried:
for label_idx in range(1, len(labels)-1):
labels[label_idx].set_text('')
which also removed all labels. I want all ticks but only the labels 0
and 8
to show up, i.e. remove the labels 2
, 4
and 6
.
I'm using Python 3.9.12 with matplotlib 3.5.2 on a Spyder 5.3.2 IDE. After upgrading to Python 3.9.15 and matplotlib 3.5.3 the issue remains.
The code in Bhargav's answer generates the same issue on my system: it removes all labels for me. I'm going to presume this is a bug in Python, matplotlib or Spyder.