从值列表中设置刻度标签

使用ax.set_xticks会导致在当前选择的刻度上设置刻度标签。 但是,您可能希望允许matplotlib动态选择刻度数及其间距。

在这种情况下,最好从刻度线上的值确定刻度标签。 以下示例显示了如何执行此操作。

注意:这里使用MaxNLocator来确保刻度值取整数值。

从值列表中设置刻度标签示例

  1. import matplotlib.pyplot as plt
  2. from matplotlib.ticker import FuncFormatter, MaxNLocator
  3. fig, ax = plt.subplots()
  4. xs = range(26)
  5. ys = range(26)
  6. labels = list('abcdefghijklmnopqrstuvwxyz')
  7. def format_fn(tick_val, tick_pos):
  8. if int(tick_val) in xs:
  9. return labels[int(tick_val)]
  10. else:
  11. return ''
  12. ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
  13. ax.xaxis.set_major_locator(MaxNLocator(integer=True))
  14. ax.plot(xs, ys)
  15. plt.show()

下载这个示例