如何使用 python matplotlib 在 y 轴上正确绘制时间?

How to plot time on the y axis correctly using python matplotlib?

我有两个列表,其中包含日落和日出时间以及相应的日期。 看起来像:

sunrises = ['06:30', '06:28', '06:27', ...]
dates = ['3.21', '3.22', '3.23', ...]

我想绘制日出时间为 Y 轴、日期为 X 轴的图。 只需使用

ax.plot(dates, sunrises)
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(7))
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(7))
plt.show()

可以正确绘制日期,但时间错误:

实际上,日出时间不应该是一条直线。

如何解决这个问题?

这是因为您的 sunrises 不是数字。我假设您希望它们采用 "6:30" 表示 6.5 的形式。计算如下:

import matplotlib.pyplot as plt

sunrises = ['06:30', '06:28', '06:27']
# This converts to decimals
sunrises = [float(x[0:2])+(float(x[-2:])/60) for x in sunrises]
dates = ['3.21', '3.22', '3.23']

plt.plot(sunrises, dates)
plt.xlabel('sunrises')
plt.ylabel('dates')
plt.show()


请注意,您的 dates 被视为小数。这是正确的吗?

您需要使用 datetime

将字符串格式的日期时间转换为 matplotlib 可以理解的格式
from matplotlib import pyplot as plt 
import matplotlib as mpl
from datetime import datetime
import matplotlib.dates as mdates

sunrises = ['06:30', '06:28', '06:27',]
sunrises_dt = [datetime.strptime(item,'%H:%M') for item in sunrises]
dates = ['3.21', '3.22', '3.23',]

fig,ax = plt.subplots()
ax.plot(dates, sunrises_dt)
ax.yaxis.set_major_formatter(mdates.DateFormatter('%H:%M',))
ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(1))

plt.show()