python - Pyplot 的刻度值可以被自动间隔整除吗?

标签 python matplotlib

有没有办法强制 pyplot (matplotlib) 的刻度值可被自动刻度间隔整除?

我真的很喜欢 pyplot 可以根据数据自动调整刻度间隔,所以我不必关心它。但我真的希望它确实使用可被该间隔整除的值。

例如,如果它决定间隔为 5,则应使用值 5,10,15,20...,而不是像下面的示例中那样使用 4,9,14,19。我怎样才能轻松修复它?

Nice interval but not at divisible values

最佳答案

您可以使用matplotlib.ticker.Locator类在任何您想要的位置找到您的刻度。具体来说,在您的情况下,我想您想使用 MultipleLocator 。只需添加到您的程序中即可

from matplotlib.ticker import MultipleLocator
ax = plt.gca()
ax.get_xaxis().set_major_locator(MultipleLocator(base=5))

一切就都准备好了。

更新:

要获取基准,您可以检查默认的 AutoLocator 刻度位置(在调用 plt.plot 之后)并获取位于旁边的任何一个刻度位置之间的差异彼此:

ticks = ax.get_xticks()
base = ticks[1] - ticks[0]

关于python - Pyplot 的刻度值可以被自动间隔整除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37151365/

相关文章:

python - numpy 矩阵乘法

python - Python-将完整路径复制到目标文件夹并保留路径结构

python - 使用 .save() 方法和 matplotlib.animation.ArtistAnimation() 保存 .gif IndexError

python - PyQt5 中的 Matplotlib : How to remove the small space along the edge

python - 无法使用 np.where() 在复杂的 2D Python 数组中查找元素的索引

python - 带有固定种子的 scipy.sparse.linalg.eigsh

python - 线程 Thread-4 中的异常 - 查找原因或捕获异常

Matplotlib 表格格式 - 更改行标签单元格的宽度

python - Matplotlib:等高线水平作为颜色条中的线

python - matplotlib 中 plt.draw() 和 plt.show() 的区别