关于python:减少绘图刻度的数量

reducing number of plot ticks

我的图表上有太多的刻度线,它们相互碰撞。

如何减少蜱的数量?

例如,我有蜱:

1
1E-6, 1E-5, 1E-4, ... 1E6, 1E7

我只想要:

1
1E-5, 1E-3, ... 1E5, 1E7

我试过玩LogLocator,但我还没弄清楚这一点。


或者,如果你想简单地设置滴答数,同时允许matplotlib定位它们(??目前只有MaxNLocator),那么有pyplot.locator_params

1
pyplot.locator_params(nbins=4)

您可以在此方法中指定特定轴,如下所述,默认为:

1
2
3
# 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)


如果有人仍在搜索结果中显示此页面:

1
2
3
4
5
6
7
8
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)


轴对象有一个set_ticks()函数。


要解决滴答的自定义和外观问题,请参阅matplotlib网站上的Tick Locators指南

<5233>

将x轴上的刻度总数设置为3,并将其均匀分布在轴上。

还有一个很好的教程


如果有人仍然需要它,从来没有
这里真的对我有用,我想出了一个非常好的
保持外观的简单方法
在修复数字时"按原样"生成情节
的刻度恰好是N:

1
2
3
4
5
6
7
8
import numpy as np
import matplotlib.pyplot as plt

f, ax = plt.subplots()
ax.plot(range(100))

ymin, ymax = ax.get_ylim()
ax.set_yticks(np.round(np.linspace(ymin, ymax, N), 2))


@raphael给出的解决方案很简单,非常有帮助。

但是,显示的刻度标签不是从原始分布中采样的值,而是来自np.linspace(ymin, ymax, N)返回的数组的索引。

要显示与原始刻度标签均匀间隔的N个值,请使用set_yticklabels()方法。这是y轴的片段,带有整数标签:

1
2
3
4
5
6
7
8
9
import numpy as np
import matplotlib.pyplot as plt

ax = plt.gca()

ymin, ymax = ax.get_ylim()
custom_ticks = np.linspace(ymin, ymax, N, dtype=int)
ax.set_yticks(custom_ticks)
ax.set_yticklabels(custom_ticks)


使用对数刻度时,可以使用以下命令修复主刻度数

1
2
3
4
5
6
import matplotlib.pyplot as plt

....

plt.locator_params(numticks=12)
plt.show()

设置为numticks的值确定要显示的轴刻度数。

致@bgamari的帖子介绍locator_params()函数,但nticks参数在使用日志比例时会引发错误。