减少绘图刻度数量
我在图表上有太多的刻度线,它们互相挤在一起了。
我该怎么减少刻度线的数量呢?
比如说,我现在有这些刻度线:
1E-6, 1E-5, 1E-4, ... 1E6, 1E7
而我只想要:
1E-5, 1E-3, ... 1E5, 1E7
我试着调整过 LogLocator
,但还是没搞明白该怎么做。
10 个回答
108
如果有人在搜索结果中仍然看到这个页面:
fig, ax = plt.subplots()
plt.plot(...)
every_nth = 4
for n, label in enumerate(ax.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
133
要解决自定义和调整刻度外观的问题,可以查看matplotlib网站上的刻度定位器指南
ax.xaxis.set_major_locator(plt.MaxNLocator(3))
这段代码会把x轴上的刻度总数设置为3,并且让它们在轴上均匀分布。
还有一个很不错的教程可以参考。
352
另外,如果你想简单地设置刻度的数量,同时让matplotlib自己来安排这些刻度的位置(目前只支持MaxNLocator
),你可以使用pyplot.locator_params
。
pyplot.locator_params(nbins=4)
在这个方法中,你可以指定具体的坐标轴,下面会提到,默认情况下是同时作用于两个坐标轴的:
# To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)