简体   繁体   English

使用matplotlib在y轴上绘制24小时的时间序列

[英]Plotting a times series using matplotlib with 24 hours on the y-axis

If I run the following, it appears to work as expected, but the y-axis is limited to the earliest and latest times in the data. 如果我运行以下命令,它似乎可以正常工作,但是y轴仅限于数据中最早和最新的时间。 I want it to show midnight to midnight. 我希望它显示从午夜到午夜。 I thought I could do that with the code that's commented out. 我以为我可以用注释掉的代码来做到这一点。 But when I uncomment it, I get the correct y-axis, yet nothing plots. 但是,当我取消注释时,我得到了正确的y轴,但没有任何图形。 Where am I going wrong? 我要去哪里错了?

from datetime import datetime
import matplotlib.pyplot as plt

data = ['2018-01-01 09:28:52', '2018-01-03 13:02:44', '2018-01-03 15:30:27', '2018-01-04 11:55:09']
x = []
y = []

for i in range(0, len(data)):
    t = datetime.strptime(data[i], '%Y-%m-%d %H:%M:%S')
    x.append(t.strftime('%Y-%m-%d')) # X-axis = date
    y.append(t.strftime('%H:%M:%S')) # Y-axis = time

plt.plot(x, y, '.')
# begin = datetime.strptime('00:00:00', '%H:%M:%S').strftime('%H:%M:%S')
# end   = datetime.strptime('23:59:59', '%H:%M:%S').strftime('%H:%M:%S')
# plt.ylim(begin, end)
plt.show()

Edit: I also noticed that the x-axis isn't right either. 编辑:我还注意到x轴也不正确。 The data skips Jan 2, but I want that on the axis so the data is to scale. 数据跳过1月2日,但我希望在轴上显示,以便按比例缩放数据。

This is a dramatically simplified version of code dealing with over a year's worth of data with over 2,500 entries. 这是大大简化的代码版本,可处理超过2500个条目的一年数据。

If Pandas is available to you, consider this approach: 如果您可以使用熊猫,请考虑以下方法:

import pandas as pd
data = pd.to_datetime(data, yearfirst=True)
plt.plot(data.date, data.time)
_=plt.ylim(["00:00:00", "23:59:59"])

情节

Update per comments 每个评论更新
X-axis date formatting can be adjusted using the Locator and Formatter methods of the matplotlib.dates module. 可以使用matplotlib.dates模块的LocatorFormatter方法调整X轴日期格式。 Locator finds the tick positions, and Formatter specifies how you want the labels to appear. Locator找到刻度位置, Formatter指定希望标签显示的方式。

Sometimes Matplotlib/Pandas just gets it right, other times you need to call out exactly what you want using these extra methods. 有时Matplotlib / Pandas正确无误,而其他时候,您需要使用这些额外的方法确切地指出所需的内容。 In this case, I'm not sure why those numbers are showing up, but this code will remove them. 在这种情况下,我不确定为什么会显示这些数字,但是此代码会将其删除。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

f, ax = plt.subplots()
data = pd.to_datetime(data, yearfirst=True)
ax.plot(data.date, data.time)
ax.set_ylim(["00:00:00", "23:59:59"])

days = mdates.DayLocator()
d_fmt = mdates.DateFormatter('%m-%d')
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(d_fmt) 

情节2

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

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