繁体   English   中英

Matplotlib plot 时间重叠标签

[英]Matplotlib plot time overlapping labels

所以我有 2 个值列表:一个带有温度值(templist),一个带有时间值(timelist)。

我将此代码用于 plot 的值:

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)

您可以指定旋转 xtick label,如下所示:

times = np.arange(10, 27, 1)
templist = np.sin(times)
bettertime = ["10:"+repr(time) for time in times] # make string for the xlabel, since that's what the question states

fig, ax = plt.subplots()
ax.plot(bettertime, templist)
plt.xticks(rotation=45)         # here's the line that does the rotation

在此处输入图像描述

您可以尝试旋转 xticks 值。 plt.xticks(rotation=45) # 90 ---> vertical xticks

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.xticks(rotation=45)   # Add this line for xticks to be rotated
plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM