Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 绘制日期时间索引数据时,在特定日期(如周末)的绘图中放置标记_Python_Matplotlib_Pandas - Fatal编程技术网

Python 绘制日期时间索引数据时,在特定日期(如周末)的绘图中放置标记

Python 绘制日期时间索引数据时,在特定日期(如周末)的绘图中放置标记,python,matplotlib,pandas,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_dat

我创建了一个带有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)

            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
通过执行以下操作,我可以轻松绘制带有熊猫的
A
柱:

df.plot()
plt.show()
它绘制了
a
列的一行,但省略了
weekend
列,因为它不包含数字数据


我如何在
a
列的每个点上放置一个“标记”,其中
weekend
列的值为
yes

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


现在,红色圆点标记所有周末,这些周末由
df.weekend='yes'
值给出。

您可以使用
df['a'][df['weekend']=='yes'].plot(style='ro')
将其缩短一点。plot(style='ro')虽然可读性更强(依我看),但还是很好的自我回答。
plt.plot(df.index, df.A)
plt.plot(df[df.weekend=='yes'].index, df[df.weekend=='yes'].A, 'ro')