Matplotlib刻度标签精度

时间:2018-08-14 16:18:34

标签: python-3.x matplotlib

定义刻度标签时,我得到了异常高的精度。例如:

import pylab as pl

fig = pl.figure(figsize=(3.25, 2.5))
ax0 = fig.add_subplot(111)

ax0.set_ylim([0, 0.5])
ax0.set_yticks(np.arange(0, 0.51, 0.1), minor=False)
ax0.set_yticklabels(np.arange(0, 0.51, 0.1), fontsize=8)

ax0.set_xlim([0, 0.5])
ax0.set_xticks(np.arange(0, 0.51, 0.1), minor=False)
ax0.set_xticklabels(np.arange(0, 0.51, 0.1), fontsize=8)

fig.show()

下面是输出图,在0.3标记(x轴和y轴)上带有错误的刻度标记。我试过使用np.linspace,它会产生相同的问题。

我了解浮点精度的问题,但我希望标签能尽快四舍五入。我该如何纠正以仅显示第一个小数?

使用matplotlib 2.2.2 Figure with bad labels.

2 个答案:

答案 0 :(得分:1)

我今天正在为此而苦苦挣扎,这是我目前的解决方案:

v1:

from matplotlib.ticker import FormatStrFormatter
ax0.set_xlim([0, 0.5])
ax0.set_xticks(np.arange(0, 0.51, 0.1), minor=False)
ax0.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))

v2:

ax0.set_xlim([0, 0.5])
ax0.set_xticks(np.round(np.arange(0, 0.51, 0.1),2), minor=False)
ax0.set_xticklabels(np.round(np.arange(0, 0.51, 0.1),2), fontsize=8)

我不确定格式化程序是在set_xlim之前还是之后,但是应该可以:)

答案 1 :(得分:1)

如果您没有手动设置刻度,刻度将自动正确标记

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(3.25, 2.5))
ax0 = fig.add_subplot(111)

ax0.set_ylim([0, 0.5])
ax0.set_yticks(np.arange(0, 0.51, 0.1), minor=False)

ax0.set_xlim([0, 0.5])
ax0.set_xticks(np.arange(0, 0.51, 0.1), minor=False)


plt.show()

enter image description here