I want to make some modifications to a few selected tick labels in a plot.
For example, if I do:
label = axes.yaxis.get_major_ticks().label
from pylab import *
axes = figure().add_subplot(111)
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
for ticklabel in axes.get_xticklabels():
Caveat: Unless the ticklabels are already set to a string (as is usually the case in e.g. a boxplot), this will not work with any version of matplotlib newer than
1.1.0. If you're working from the current github master, this won't work. I'm not sure what the problem is yet... It may be an unintended change, or it may not be...
Normally, you'd do something along these lines:
import matplotlib.pyplot as plt fig, ax = plt.subplots() # We need to draw the canvas, otherwise the labels won't be positioned and # won't have values yet. fig.canvas.draw() labels = [item.get_text() for item in ax.get_xticklabels()] labels = 'Testing' ax.set_xticklabels(labels) plt.show()
To understand the reason why you need to jump through so many hoops, you need to understand a bit more about how matplotlib is structured.
Matplotlib deliberately avoids doing "static" positioning of ticks, etc, unless it's explicitly told to. The assumption is that you'll want to interact with the plot, and so the bounds of the plot, ticks, ticklabels, etc will be dynamically changing.
Therefore, you can't just set the text of a given tick label. By default, it's re-set by the axis's Locator and Formatter every time the plot is drawn.
However, if the Locators and Formatters are set to be static (
FixedFormatter, respectively), then the tick labels stay the same.
This is what
Hopefully that makes it slighly more clear as to why changing an individual tick label is a bit convoluted.
Often, what you actually want to do is just annotate a certain position. In that case, look into