from pylab import*
axes = figure().add_subplot(111)
t = arange(0.0,2.0,0.01)
s = sin(2*pi*t)
axes.plot(t, s)for ticklabel in axes.get_xticklabels():print ticklabel.get_text()
the font size and the orientation of the tick label is changed.
However, if try:
label.set_text('Foo')
the tick label is not modified. Also if I do:
print label.get_text()
nothing is printed.
Here’s some more strangeness. When I tried this:
from pylab import *
axes = figure().add_subplot(111)
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
axes.plot(t, s)
for ticklabel in axes.get_xticklabels():
print ticklabel.get_text()
Only empty strings are printed, but the plot contains ticks labeled as ‘0.0’, ‘0.5’, ‘1.0’, ‘1.5’, and ‘2.0’.
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[1]='Testing'
ax.set_xticklabels(labels)
plt.show()
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[1] = '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 (FixedLocator and FixedFormatter, respectively), then the tick labels stay the same.
This is what set_*ticklabels or ax.*axis.set_ticklabels does.
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 annotate, instead.
回答 1
pylab和xticks也可以做到这一点
import matplotlib
import matplotlib.pyplot as plt
x =[0,1,2]
y =[90,40,65]
labels =['high','low',37337]
plt.plot(x,y,'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()
>>>from pylab import*>>> axes = figure().add_subplot(111)>>> a=axes.get_xticks().tolist()>>> a[1]='change'>>> axes.set_xticklabels(a)[<matplotlib.text.Text object at 0x539aa50>,<matplotlib.text.Text object at 0x53a0c90>,<matplotlib.text.Text object at 0x53a73d0>,<matplotlib.text.Text object at 0x53a7a50>,<matplotlib.text.Text object at 0x53aa110>,<matplotlib.text.Text object at 0x53aa790>]>>> plt.show()
结果:
现在,如果您进行检查_xticklabels,它们不再是一堆''。
>>>[item.get_text()for item in axes.get_xticklabels()]['0.0','change','1.0','1.5','2.0']
In newer versions of matplotlib, if you do not set the tick labels with a bunch of str values, they are '' by default (and when the plot is draw the labels are simply the ticks values). Knowing that, to get your desired output would require something like this:
>>> from pylab import *
>>> axes = figure().add_subplot(111)
>>> a=axes.get_xticks().tolist()
>>> a[1]='change'
>>> axes.set_xticklabels(a)
[<matplotlib.text.Text object at 0x539aa50>, <matplotlib.text.Text object at 0x53a0c90>,
<matplotlib.text.Text object at 0x53a73d0>, <matplotlib.text.Text object at 0x53a7a50>,
<matplotlib.text.Text object at 0x53aa110>, <matplotlib.text.Text object at 0x53aa790>]
>>> plt.show()
and the result:
and now if you check the _xticklabels, they are no longer a bunch of ''.
>>> [item.get_text() for item in axes.get_xticklabels()]
['0.0', 'change', '1.0', '1.5', '2.0']
It works in the versions from 1.1.1rc1 to the current version 2.0.
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
def update_ticks(x, pos):if x ==0:return'Mean'elif pos ==6:return'pos is 6'else:return x
data = np.random.normal(0,1,1000)
fig, ax = plt.subplots()
ax.hist(data, bins=25, edgecolor='black')
ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
plt.show()
It’s been a while since this question was asked. As of today (matplotlib 2.2.2) and after some reading and trials, I think the best/proper way is the following:
Matplotlib has a module named ticker that “contains classes to support completely configurable tick locating and formatting”. To modify a specific tick from the plot, the following works for me:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
def update_ticks(x, pos):
if x == 0:
return 'Mean'
elif pos == 6:
return 'pos is 6'
else:
return x
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=25, edgecolor='black')
ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
plt.show()
Caveat!x is the value of the tick and pos is its relative position in order in the axis. Notice that pos takes values starting in 1, not in 0 as usual when indexing.
In my case, I was trying to format the y-axis of a histogram with percentage values. mticker has another class named PercentFormatter that can do this easily without the need to define a separate function as before:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
weights = np.ones_like(data) / len(data)
ax.hist(data, bins=25, weights=weights, edgecolor='black')
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=1))
plt.show()
In this case xmax is the data value that corresponds to 100%. Percentages are computed as x / xmax * 100, that’s why we fix xmax=1.0. Also, decimals is the number of decimal places to place after the point.
#ax is the axes instance
group_labels =['control','cold treatment','hot treatment','another treatment','the last one']
ax.set_xticklabels(group_labels)
The axes class has a set_yticklabels function which allows you to set the tick labels, like so:
#ax is the axes instance
group_labels = ['control', 'cold treatment',
'hot treatment', 'another treatment',
'the last one']
ax.set_xticklabels(group_labels)
I’m still working on why your example above didn’t work.