需要对以下数据进行绘图,时间是X轴,price是Y轴。
t_time = ['11:10:00', '11:11:00', '11:12:00', '11:13:00', '11:14:00', '11:15:00', '11:16:00', '11:17:00']
price = [120.3294479, 123.0510004, 135.7725529, 135.5874355, 137.817284, 140.0471325, 145.3769811, 150.5639725]
直接使用时间字符串绘图,会X轴数据重叠显示。
因此,将时间转换为datetime对象而不是字符串,然后使用matplotlib.mdates.DateFormatter()转换为适当的日期格式。
import matplotlib.dates as mdates
import datetime
fmt = mdates.DateFormatter('%H:%M:%S')
price = [datetime.datetime.strptime(i, '%H:%M:%S') for i in price]
fig, ax = plt.subplots()
plt.plot(t_time,price,'r', label='values over time')
ax.xaxis.set_major_formatter(fmt)
plt.show()