【问题标题】:Matplotlib plot time overlapping labelsMatplotlib 绘制时间重叠标签
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 这可能是一个解决方案,但如果我有一个只有 5 个数据的列表,我认为这将是一个问题
【解决方案2】:

您可以尝试旋转 xticks 值。 plt.xticks(rotation=45) # 90 ---&gt; 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()

【讨论】: