如何使用matplotlib在小时图上以分钟精度绘制事件?

时间:2018-10-24 16:49:06

标签: python-3.x datetime matplotlib

我有一个使用matplotlib生成的每小时图表。我需要绘制一个事件,例如从09:00到10:45。当我尝试使用axvspan时,我会在9:00到10:00之间获得一个酒吧。如何获得更长的呢?

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import datetime as dt
import pandas as pd

now_date = dt.datetime(2018,10,1,9)
d_tw_ini = now_date - dt.timedelta(hours = 1)
d_tw_fin = now_date + dt.timedelta(hours = 3)

dts = pd.date_range(start=d_tw_ini, end=d_tw_fin, freq='1H', name='ini', closed='left')
data=pd.DataFrame({'val':[0.5,0.4,0.7,0.9]})

ev1=[dt.datetime(2018,10,1,9,5),dt.datetime(2018,10,1,10,50)]

data['t']=dts.values
data.set_index('t',inplace=True)

fig = plt.figure()
gs = GridSpec(1, 1)
ax_1 = fig.add_subplot(gs[0, 0])

data.plot(ax=ax_1, y='val')
ax_1.axvspan(ev1[0],ev1[1], alpha=0.3, color= 'red')

Result

1 个答案:

答案 0 :(得分:0)

Juan,当您使用pandas to plot时,每小时的索引编制似乎会导致axvspan的绘制方式出现问题。

我替换了

data.plot(ax=ax_1, y='val')

使用

ax_1.plot(data.index, data['val'])

它会生成下面的图像,但不幸的是,您失去了自动的x轴格式。

enter image description here

将以下两行相加将产生与您的示例相同的日期格式。

ax_1.set_xticks([x for x in data.index])
ax_1.set_xticklabels([str(x)[11:16] for x in data.index])

enter image description here

下面是产生以上曲线的完整代码。

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import datetime as dt
import pandas as pd

now_date = dt.datetime(2018,10,1,9)
d_tw_ini = now_date - dt.timedelta(hours = 1)
d_tw_fin = now_date + dt.timedelta(hours = 3)

dts = pd.date_range(start=d_tw_ini, end=d_tw_fin, freq='1h', name='ini', 
closed='left')
data=pd.DataFrame({'val':[0.5,0.4,0.7,0.9]})

ev1=[dt.datetime(2018,10,1,9,5,0),dt.datetime(2018,10,1,10,50,0)]

data['t']=dts.values
data.set_index('t',inplace=True)

fig = plt.figure()
gs = GridSpec(1, 1)
ax_1 = fig.add_subplot(gs[0, 0])

# modified section below
ax_1.plot(data.index, data['val'])
ax_1.axvspan(ev1[0],ev1[1], alpha=0.3, color= 'red')

ax_1.set_xticks([x for x in data.index])
ax_1.set_xticklabels([str(x)[11:16] for x in data.index])

plt.show()