Matplotlib显示错误的y轴值

3

My code is very simple:

values = [-2071238, -2071241, -2071240, -2071242, -2071244, -2071239, -2071221, -2071194, -2071224, -2071240, -2071244, -2071241, -2071240, -2071241, -2071237, -2071223, -2071205, -2071225, -2071238]
indx = [0.0, 20.0, 40.0, 60.0, 80.0, 100.0, 120.0, 140.0, 160.0, 180.0, 200.0, 220.0, 240.0, 260.0, 280.0, 300.0, 320.0, 340.0, 360.0]

plt.scatter(indx, values)

#rendering
plt.xlabel("Axis 1")
plt.ylabel("Axis 2")
title = "All"
plt.title(title)
plt.savefig(title + ".png")
plt.show()

然而,得到的图形如下:

picture

很明显,每个点的y值都不太好。

我是做错了什么还是忘记了什么?

1个回答

5

您的图表y轴数值很好,但它们存在一个偏移。该偏移可以禁用:

import matplotlib.pyplot as plt

values = [-2071238, -2071241, -2071240, -2071242, -2071244, -2071239, -2071221, -2071194, -2071224, -2071240, -2071244, -2071241, -2071240, -2071241, -2071237, -2071223, -2071205, -2071225, -2071238]
indx = [0.0, 20.0, 40.0, 60.0, 80.0, 100.0, 120.0, 140.0, 160.0, 180.0, 200.0, 220.0, 240.0, 260.0, 280.0, 300.0, 320.0, 340.0, 360.0]

plt.scatter(indx, values)

# disabling the offset on y axis
ax = plt.gca()
ax.ticklabel_format(useOffset=False)

#rendering
plt.xlabel("Axis 1")
plt.ylabel("Axis 2")
title = "All"
plt.title(title)
plt.savefig(title + ".png")

plt.show()

enter image description here


我不明白偏移量怎么可能是正确的。大部分时间它都与负值相乘,所以我认为结果应该是正数? - Antys
@Antys - 偏移量意味着你的图表上的0刻度被移动并等于-2071200(与-2.0712e6相同)。当分配给y轴刻度的值加上偏移量时,它们会得到与我添加到图表上的相同的值(例如-2071200 + (-10) = -2071210)。你的问题是你试图将偏移量乘以分配给刻度的值,而不是将它们相加。 - machnic
1
一个重要的补充说明:如果你的坐标轴之一是日期,上面对 ax.ticklabel_format 的调用 useOffset=False 将会失败。在这种情况下,你需要明确指定不是日期轴的轴,使用 ax.ticklabel_format(axis="y", useOffset=False)(这里,x是日期轴)。原因是轴参数默认设置为"both",否则 ax.ticklabel_format 将会抛出 "This method only works with the ScalarFormatter" 的异常。 - MrCC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接