简体   繁体   English

Matplotlib plot 时间重叠标签

[英]Matplotlib plot time overlapping labels

So I have 2 lists of values: one with temperature values (templist) and one with time values (timelist).所以我有 2 个值列表:一个带有温度值(templist),一个带有时间值(timelist)。

I use this code to plot the values:我将此代码用于 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()

And when I run it, I got this results:当我运行它时,我得到了这个结果:

绘图结果

The values on the time ax are not displayed correctly.时间轴上的值显示不正确。 I also tried with, but I just got the values cut (just plotting the first 10 values):我也试过了,但我只是把值删掉了(只是绘制了前 10 个值):

ax.set(xlim=(0, 10))

So after some research I found that my list of time (timelist) is a list of strings, not datetime formatted so matplotlib doesn't know how to shrink it down.因此,经过一番研究,我发现我的时间列表(时间列表)是一个字符串列表,而不是日期时间格式,所以 matplotlib 不知道如何缩小它。

How can I fit the values in the graph?如何拟合图表中的值? (For the example, templist got automatic fitted on the Y ax) (I want to get like 10 values of time in the graph, but from maxim to minim, not just first 10 values of the list) (例如,templist 自动安装在 Y 轴上)(我想在图中获得 10 个时间值,但从最大值到最小值,而不仅仅是列表的前 10 个值)

And as a side note, the lists (timelist and templist) are lists of random length (equal length, len(timelist) is equal with len(timelist) if this is important at all)附带说明一下,列表(timelist 和 templist)是随机长度的列表(长度相等,如果这很重要,则 len(timelist) 与 len(timelist) 相等)

EDIT:编辑:

The solution:解决方案:

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)

You can specify that the xtick label be rotated, like this:您可以指定旋转 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

在此处输入图像描述

You can try rotating your xticks value.您可以尝试旋转 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