Matplotlib 轴在应该成一定角度时是垂直的……直到我更改图表的 dates/times

Matplotlib axline is vertical when it should be at an angle...until I change the dates/times for the chart

我正在尝试使用 Matplotlib 在图表上绘制一条斜线,但有时它只是错误地绘制了一条垂直线。 dates/times 似乎有问题。这就像在正确绘制之前点之间需要最短时间。任何人都可以阐明这一点吗?

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

time = 1652536320  # Start time
unix_time = [time]

for i in range(4):
    time += 16525
    # There must be 16526 seconds (4.5 hours) between unix timestamps for the axline to plot correctly.
    # Anything less incorrectly produces a vertical line.
    unix_time.append(time)

non_unix_time = []
for t in unix_time:
    dt = datetime.datetime.fromtimestamp(t)
    converted = mdates.date2num(dt)
    non_unix_time.append(converted)

print(unix_time)
print(non_unix_time)

fig = plt.figure()

ax3 = plt.subplot2grid((1, 1), (0, 0))

x = non_unix_time
y = [29675, 29813, 29840, 29761, 29746]

ax3.axline((non_unix_time[0], 29600), (non_unix_time[1], 29800))

ax3.plot(x, y)

plt.show()

如果不深入挖掘,很难弄清发生这种情况的原因。使用date2num转换时,时间戳变成十进制数,如19126.661111111112.

画线时,matplotlibchecks whether the points are "close" in the coordinate space with respect to their magnitude using the np.allclose()函数。如果它们很接近,则直线的斜率会自动设置为 np.inf 并绘制一条垂直线。现在,在您的情况下,您确实可以看到在 16526 秒的阈值差异下,这些点被认为是“接近”:

import numpy as np

# Testing with non_unix_time[0] and non_unix_time[1].
# Same as: print(np.allclose(19126.661111111112, 19126.852372685185))
# Prints True. 
print(np.allclose(non_unix_time[0], non_unix_time[1]))

如果你用更大的差异进行测试,这将打印 False。您的解决方案是使用单点和 slope 参数并自己计算正确的斜率:

slope = (29800 - 29600)/(non_unix_time[1] - non_unix_time[0])

#ax3.axline((non_unix_time[0], 29600), (non_unix_time[1], 29800))
ax3.axline((non_unix_time[0], 29600), slope=slope)

并且该线将被正确绘制: