我注意到这里发布的所有使用set_xticklabels()的解决方案都没有保留偏移量,偏移量是应用于tick值以创建更好看的tick标签的缩放因子。例如,如果刻度在0.00001 (1e-5)量级,matplotlib将自动添加1e-5的缩放因子(或偏移量),因此最终的刻度标签可能是1 2 3 4,而不是1e-5 2e-5 3e-5 4e-5。
下面是一个例子:
x数组是np。数组([1,2,3,4])/1e6,并且y=x**2。所以两个值都很小。
左栏:按照@Joe Kington的建议手动更改第1和第3个标签。注意,偏移量丢失了。
中间列:类似于@iipr的建议,使用FuncFormatter。
右栏:我建议的保留偏移量的解决方案。
图:
完整代码:
import matplotlib.pyplot as plt
import numpy as np
# create some *small* data to plot
x = np.arange(5)/1e6
y = x**2
fig, axes = plt.subplots(1, 3, figsize=(10,6))
#------------------The set_xticklabels() solution------------------
ax1 = axes[0]
ax1.plot(x, y)
fig.canvas.draw()
labels = [item.get_text() for item in ax1.get_xticklabels()]
# Modify specific labels
labels[1] = 'Testing'
labels[3] = 'Testing2'
ax1.set_xticklabels(labels)
ax1.set_title('set_xticklabels()')
#--------------FuncFormatter solution--------------
import matplotlib.ticker as mticker
def update_ticks(x, pos):
if pos==1:
return 'testing'
elif pos==3:
return 'testing2'
else:
return x
ax2=axes[1]
ax2.plot(x,y)
ax2.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
ax2.set_title('Func Formatter')
#-------------------My solution-------------------
def changeLabels(axis, pos, newlabels):
'''Change specific x/y tick labels
Args:
axis (Axis): .xaxis or .yaxis obj.
pos (list): indices for labels to change.
newlabels (list): new labels corresponding to indices in <pos>.
'''
if len(pos) != len(newlabels):
raise Exception("Length of <pos> doesn't equal that of <newlabels>.")
ticks = axis.get_majorticklocs()
# get the default tick formatter
formatter = axis.get_major_formatter()
# format the ticks into strings
labels = formatter.format_ticks(ticks)
# Modify specific labels
for pii, lii in zip(pos, newlabels):
labels[pii] = lii
# Update the ticks and ticklabels. Order is important here.
# Need to first get the offset (1e-6 in this case):
offset = formatter.get_offset()
# Then set the modified labels:
axis.set_ticklabels(labels)
# In doing so, matplotlib creates a new FixedFormatter and sets it to the xaxis
# and the new FixedFormatter has no offset. So we need to query the
# formatter again and re-assign the offset:
axis.get_major_formatter().set_offset_string(offset)
return
ax3 = axes[2]
ax3.plot(x, y)
changeLabels(ax3.xaxis, [1, 3], ['Testing', 'Testing2'])
ax3.set_title('With offset')
fig.show()
plt.savefig('tick_labels.png')
注意:使用set_xticklabels()的解决方案,包括我自己的解决方案,似乎都依赖于FixedFormatter,它是静态的,不响应图形调整大小。为了观察效果,将图形更改为较小的尺寸,例如fig, axes = plt。Subplots (1,3, figsize=(6,6))并放大图形窗口。您将注意到,只有中间列响应调整大小,并随着图形变大而添加更多刻度。左边和右边的列将有空的标记(见下图)。
警告2:我还注意到,如果tick值是浮点数,直接调用set_xticklabels(ticks)可能会得到难看的字符串,比如1.499999999998而不是1.5。