matplotlib:使用时间绘图并忽略年/月/日

时间:2013-12-16 16:22:32

标签: python matplotlib

我是Python / matplotlib的新手所以请耐心等待! 我有几天的纪元时间戳列表和一个表示事件是否发生的布尔值。我想用matplotlib绘制这个,在x轴上显示时间,Y轴显示1/0,我看到了这样做的例子Plotting time in Python with Matplotlib

但是,我想忽略yr / month / date并再次绘制时间,即1-Dec的8 AM时间和2-Dec的8 AM时间使用相同的X轴坐标。

编辑:这是当前代码:

import time
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

event = [
(1384528771000000000, 1),
(1384550132000000000, 0),
(1384881104000000000, 0),
(1384962750000000000, 1),
(1384966615000000000, 1),
(1385049149000000000, 1),
(1385053051000000000, 0),
(1385053939000000000, 0),
(1385140573000000000, 1),
(1385393839000000000, 1),
(1385398965000000000, 0),
(1385410739000000000, 1),
(1385483309000000000, 1),
(1385587272000000000, 0),
(1385998456000000000, 1),
(1386084047000000000, 0),
(1386085865000000000, 1),
(1386259016000000000, 0),
(1386345606000000000, 0),
(1386602368000000000, 1)
]

for line in event:
    timeStmp = datetime.datetime.strptime(time.ctime(line[0]/1000000000), "%a %b %d %H:%M:%S %Y")
    print timeStmp, mdates.date2num(timeStmp)
    plt.plot_date(mdates.date2num(timeStmp),line[1])
plt.show()

2 个答案:

答案 0 :(得分:1)

所以我在这里做的另一件事就是采用你的日期/时间标记,转换为一串时间数据,然后使用mdates将该时间字符串转换为数字。粗暴和低效,但我认为这是你想要的。

for line in event:
    datetimeStamp = datetime.datetime.strptime(time.ctime(line[0]/1000000000), "%a %b %d %H:%M:%S %Y")
    timeStamp = datetimeStamp.strftime('%H:%M:%S')

    print(timeStamp, mdates.datestr2num(timeStamp))
    plt.plot_date(mdates.datestr2num(timeStamp),line[1])
plt.show()

答案 1 :(得分:0)

这是一种方法,只需绘制当天开始时间与时间戳中时间之间的时差:

import time
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib

event = [
(1384528771000000000, 1),
(1384550132000000000, 0),
(1384881104000000000, 0),
(1384962750000000000, 1),
(1384966615000000000, 1),
(1385049149000000000, 1),
(1385053051000000000, 0),
(1385053939000000000, 0),
(1385140573000000000, 1),
(1385393839000000000, 1),
(1385398965000000000, 0),
(1385410739000000000, 1),
(1385483309000000000, 1),
(1385587272000000000, 0),
(1385998456000000000, 1),
(1386084047000000000, 0),
(1386085865000000000, 1),
(1386259016000000000, 0),
(1386345606000000000, 0),
(1386602368000000000, 1)
]

fig = plt.figure()
ax = fig.add_subplot(111)

for line in event:
    timeStmp = datetime.datetime.strptime(time.ctime(line[0]/1000000000), "%a %b %d %H:%M:%S %Y")
    print timeStmp, mdates.date2num(timeStmp)
    tdelta = timeStmp - datetime.datetime.strptime(str(timeStmp.year) + " " + str(timeStmp.month) + " " + str(timeStmp.day) + " 00:00:00", "%Y %m %d %H:%M:%S")
    ax.plot(tdelta.total_seconds(),line[1], 'o')

def timeTicks(x, pos):
    d = datetime.timedelta(seconds=x)
    return str(d)
formatter = matplotlib.ticker.FuncFormatter(timeTicks)
ax.xaxis.set_major_formatter(formatter)
plt.show()