备注
前往结尾 下载完整示例代码。
从值列表设置刻度标签#
使用 Axes.set_xticks 会导致刻度标签被设置在当前选择的刻度上。然而,您可能希望允许 matplotlib 动态选择刻度的数量及其间距。
在这种情况下,从刻度处的值来确定刻度标签可能会更好。以下示例展示了如何做到这一点。
注意:这里使用了 ticker.MaxNLocator 以确保刻度值为整数值。
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
fig, ax = plt.subplots()
xs = range(26)
ys = range(26)
labels = list('abcdefghijklmnopqrstuvwxyz')
def format_fn(tick_val, tick_pos):
if int(tick_val) in xs:
return labels[int(tick_val)]
else:
return ''
# A FuncFormatter is created automatically.
ax.xaxis.set_major_formatter(format_fn)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.plot(xs, ys)
plt.show()

参考文献
以下示例展示了以下函数、方法、类和模块的使用: