【发布时间】:2020-04-08 05:27:13
【问题描述】:
所以我有 2 个值列表:一个带有温度值 (templist),另一个带有时间值 (timelist)。
我使用这段代码来绘制值:
n = 0
bettertime = []
sizeoflist = len(timelist)
while n < sizeoflist:
newtime = datetime.strptime(timelist[n], "%H:%M:%S")
bettertime.append(newtime.strftime("%H:%M"))
n = n + 1
fig, ax = plt.subplots()
ax.plot(bettertime, templist)
plt.show()
当我运行它时,我得到了这个结果:
时间轴上的值显示不正确。 我也试过了,但我只是把值删掉了(只是绘制了前 10 个值):
ax.set(xlim=(0, 10))
所以经过一些研究,我发现我的时间列表(时间列表)是一个字符串列表,而不是日期时间格式,所以 matplotlib 不知道如何缩小它。
如何拟合图表中的值? (例如,templist 自动安装在 Y 轴上) (我想在图中得到 10 个时间值,但从最大值到最小值,而不仅仅是列表的前 10 个值)
附带说明,列表(timelist 和 templist)是随机长度的列表(长度相等,如果这很重要,len(timelist) 与 len(timelist) 相等)
编辑:
解决办法:
fmt = mdates.DateFormatter('%H:%M')
bettertimelist = [datetime.strptime(i, '%H:%M:%S') for i in timelist]
fig.autofmt_xdate()
ax.xaxis.set_major_formatter(fmt)
【问题讨论】:
-
查看
pandas。它提供了一些将表中的列转换为日期时间的简单方法,还允许您轻松地绘制表中的列。 -
@Denziloe 这是个好主意。但我发现我可以使用更简单的方法来解决这个问题。只需将数据从简单的字符串列表转换为日期时间数组,matplotlib 就会从那里完成工作
标签: python python-3.x matplotlib plot