在绘制日期时间索引数据时,在特定日期(例如周末)将图表放入图中

Dir*_*irk 6 python matplotlib pandas

我使用DatetimeIndex创建一个pandas数据帧,如下所示:

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

# create datetime index and random data column
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=14, freq='D')
data = np.random.randint(1, 10, size=14)
columns = ['A']

df = pd.DataFrame(data, index=index, columns=columns)

# initialize new weekend column, then set all values to 'yes' where the index corresponds to a weekend day
df['weekend'] = 'no'
df.loc[(df.index.weekday == 5) | (df.index.weekday == 6), 'weekend'] = 'yes'

print(df)
Run Code Online (Sandbox Code Playgroud)

这使

            A weekend
2014-10-13  7      no
2014-10-14  6      no
2014-10-15  7      no
2014-10-16  9      no
2014-10-17  4      no
2014-10-18  6     yes
2014-10-19  4     yes
2014-10-20  7      no
2014-10-21  8      no
2014-10-22  8      no
2014-10-23  1      no
2014-10-24  4      no
2014-10-25  3     yes
2014-10-26  8     yes
Run Code Online (Sandbox Code Playgroud)

我可以通过以下方式轻松地A用大熊猫绘制柱子:

df.plot()
plt.show()
Run Code Online (Sandbox Code Playgroud)

它绘制了一A列的一行,但weekend由于它没有数字数据而遗漏了该列.

'A'但不是'周末'的情节

如何Aweekend列具有值的列的每个点上放置"标记" yes

Dir*_*irk 7

同时我发现,它就像在pandas中使用布尔索引一样简单.直接使用pyplot而不是pandas自己的绘图包装(这对我来说更方便):

plt.plot(df.index, df.A)
plt.plot(df[df.weekend=='yes'].index, df[df.weekend=='yes'].A, 'ro')
Run Code Online (Sandbox Code Playgroud)

带有周末标记的'A'图

现在,红点标记所有周末天数,由df.weekend='yes'值给出.

  • 你可以用'df ['A'] [df ['weekend'] =='yes']来缩短它的微观情节.plot(style ='ro')`有点可读性(IMO)但仍然很好自答案. (2认同)