轴号是根据给定的Formatter 定义的。不幸的是(AFAIK),matplotlib 没有公开一种方法来控制阈值从数字变为较小的数字 + 偏移量。蛮力方法是设置所有 xtick 字符串:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(100, 100.1, 100)
y = np.arange(100)
fig = plt.figure()
plt.plot(x, y)
plt.show() # original problem
# setting the xticks to have 3 decimal places
xx, locs = plt.xticks()
ll = ['%.3f' % a for a in xx]
plt.xticks(xx, ll)
plt.show()
这实际上与使用字符串设置 FixedFormatter 相同:
from matplotlib.ticker import FixedFormatter
plt.gca().xaxis.set_major_formatter(FixedFormatter(ll))
但是,这种方法的问题是标签是固定的。如果要调整绘图的大小/平移,则必须重新开始。更灵活的方法是使用 FuncFormatter:
def form3(x, pos):
""" This function returns a string with 3 decimal places, given the input x"""
return '%.3f' % x
from matplotlib.ticker import FuncFormatter
formatter = FuncFormatter(form3)
gca().xaxis.set_major_formatter(FuncFormatter(formatter))
现在您可以移动绘图并且仍然保持相同的精度。但有时这并不理想。人们并不总是想要一个固定的精度。想要保留默认的 Formatter 行为,只需将阈值增加到它开始添加偏移量的时间。没有公开的机制,所以我最终要做的是更改源代码。这很简单,只需在ticker.py 的一行中更改一个字符。如果你查看那个 github 版本,它在第 497 行:
if np.absolute(ave_oom - range_oom) >= 3: # four sig-figs
我一般改成:
if np.absolute(ave_oom - range_oom) >= 5: # four sig-figs
并发现它对我的使用效果很好。在你的 matplotlib 安装中更改那个文件,然后记得在它生效之前重启 python。