matplotlib 在时间序列数据上绘制特定日期

vkc1a9a2  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(150)

我正在尝试使用matplotlib在时间序列数据集上绘制特定日期。这些日期表示我想突出显示的一些事件。我想对多个日期进行此操作。我可以对一个日期进行此操作,但不能对多个日期进行此操作。有人能帮助我绘制多个日期吗?

from datetime import datetime
from matplotlib.dates import date2num

fig, ax = plt.subplots(figsize=(30,10))
ax.plot(df)
ax.axvspan(date2num(datetime(2022,4,8)), date2num(datetime(2022,4,8)), 
           label="Leaks",color="red", alpha=1)
ax.legend()
ax.set_ylabel('Values')
ax.set_title('Leaks in liquid Lvl', size=28)

我试过几种方法,但都不管用。

from datetime import datetime
from matplotlib.dates import date2num
from matplotlib.dates import date3num
from matplotlib.dates import date4num

fig, ax = plt.subplots(figsize=(30,10))
ax.plot(df)

ax.axvspan(date2num(datetime(2022,4,8)), date2num(datetime(2022,4,8)), date3num(datetime(2022,6,22)), date3num(datetime(2022,6,22)),date4num(datetime(2022,9,2)), date4num(datetime(2022,9,2)),
           label="Leaks",color="red", alpha=1)

ax.legend()
ax.set_ylabel('Values')
ax.set_title('Leaks in liquid Lvl', size=28)

###############################################

from datetime import datetime
from matplotlib.dates import date2num
from matplotlib.dates import date3num
from matplotlib.dates import date4num

fig, ax = plt.subplots(figsize=(30,10))
ax.plot(df)
#ax.axvspan(date2num(datetime(2022,4,8)), date2num(datetime(2022,4,8)), 
           #label="Leaks",color="red", alpha=1)
#ax.axvspan(date3num(datetime(2022,6,22)), date3num(datetime(2022,6,22)), 
           #label="Leaks",color="red", alpha=1)
#ax.axvspan(date4num(datetime(2022,9,2)), date4num(datetime(2022,9,2)), 
           #label="Leaks",color="red", alpha=1)

ax.legend()
ax.set_ylabel('Values')
ax.set_title('Leaks in liquid Lvl', size=28)
ddrv8njm

ddrv8njm1#

import matplotlib.pyplot as plt
import datetime
import pandas as pd
import numpy as np

# Generate toy data
df =pd.DataFrame({'var': np.random.randint(low = 3,high=8,size=365)}, 
        index=pd.date_range(start='2022-01-01', end='2022-12-31', freq='D'),

)

plt.figure(figsize = (10, 5))
# plot the dataframe
plt.plot(df, color='g')

# list of dattes to be hilighted
line_date =['2022-04-08','2022-06-22','2022-09-02']

for mark_time in line_date:
    time_x=pd.Timestamp(mark_time) # convert to compatible format
    plt.axvline(x = time_x, color = 'b')
plt.show()

相关问题