首页 > 解决方案 > Matplotlib tweek 标签算法?

问题描述

Matplotlib 有一些非常复杂的代码来确定如何显示标签,但有时它会限制它的标签而不是在演示中看起来很好。有没有办法tweek它?

例如,假设我们正在根据日期绘制一些东西:

figure = plt.figure(figsize=(8,1))
ax = plt.gca()
ax.set_xlim(xmin=np.datetime64('2010'), xmax=np.datetime64('2020-04-01'))

我们得到一个像这样的x轴:

x 轴紧密排列的年份

但假设我们希望它显示更多间隔年份,如下所示:

所需轴

我们可以在任何给定的情况下通过“机械地”编辑标签来组合它。例如:

ax.set_xticks([tick for i, tick in enumerate(ax.get_xticks()) if i%2==0]) # Every other year.
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))

但这很脆弱,只要 x 限制发生变化,它就会中断。

有没有办法在刻度设置算法中强制增加间距?

标签: pythonmatplotlibaxis-labels

解决方案


哦!找到了 matplotlib 源代码,它把我带到了AutoDateLocator

ax.xaxis.set_major_locator(matplotlib.dates.AutoDateLocator(maxticks=8))

非日期的对应定位器是MaxNLocator


推荐阅读