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

ldfqzlk8  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(158)

我有一个用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')

kuarbcqp

kuarbcqp1#

Juan,看起来当你使用pandas to plot时,每小时的索引似乎会导致axvspan如何绘制的问题。
我换了
data.plot(ax=ax_1, y='val')

ax_1.plot(data.index, data['val'])
它生成了下面的图像,但不幸的是,您丢失了自动化的x轴格式。

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

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

下面是生成上述图的完整代码。

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()

相关问题