如何在时间序列轴上绘制垂直线?

时间:2020-09-27 23:41:48

标签: python pandas matplotlib

我想“链接”两段代码。一,

x= df[df['Value']==True].sort_values(by='Date').head(1).Date

Out[111]:
8    2020-03-04

提取第一个值出现的日期;另一个

df[df['Buy']==1].groupby('Date').size().plot(ax=ax, label='Buy')

应随时间绘制一些信息。

我想在第一个日期添加一个垂直线,其中该值为真,即2020-03-04。为了做到这一点,我需要从第一个代码(不使用复制和粘贴)中提取此信息到另一个生成图的代码中。 您能给我一些指导吗?非常感谢

更新:

我尝试如下:

x= df[df['Value']==True].sort_values(by='Date').head(1).Date.tolist()

Out[111]:
8    ['2020-03-04']

df[df['Buy']==1].groupby('Date').size().plot(ax=ax, label='Buy')

ax.axvline(x, color="red", linestyle="--")

但是我遇到了TypeError:无法散列的类型:'numpy.ndarray'

一些数据:

Date           Buy      Value
0   2020-02-23  0   False
1   2020-02-23  0   False
2   2020-02-25  0   False
3   2020-02-27  1   False
4   2020-03-03  1   False
5   2020-03-03  1   False
6   2020-03-03  0   False
7   2020-03-04  1   False
8   2020-03-04  0   True
9   2020-03-04  0   True
10  2020-03-04  1   False
11  2020-03-05  0   True
12  2020-03-05  1   False
13  2020-03-05  1   False
14  2020-03-05  1   False
15  2020-03-06  0   False
16  2020-03-06  1   False
17  2020-03-06  1   False
18  2020-03-07  1   False
19  2020-03-07  1   False
20  2020-03-07  1   False
21  2020-03-08  1   False
22  2020-03-08  1   False
23  2020-03-09  1   False
24  2020-03-09  1   False
25  2020-03-09  1   False
26  2020-03-10  1   False
27  2020-03-10  1   False
28  2020-03-10  1   False
29  2020-03-10  0   True
30  2020-03-11  1   False
31  2020-03-11  1   False
32  2020-03-13  0   True
33  2020-03-13  0   False
34  2020-03-15  0   True
35  2020-03-16  0   False
36  2020-03-19  0   False
37  2020-03-22  0   True

1 个答案:

答案 0 :(得分:1)

  • 确保Date列的格式为datetime
import pandas as pd
import random  # for test data
import matplotlib.pyplot as plt

# setup sample data
random.seed(365)
rows = 40
data = {'Date': [random.choice(pd.bdate_range('2020-02-23', freq='d', periods=rows).strftime('%Y-%m-%d').tolist()) for _ in range(rows)],
        'Buy': [random.choice([0, 1]) for _ in range(rows)],
        'Value': [random.choice([False, True]) for _ in range(rows)]}

df = pd.DataFrame(data)

# set the Date column to a datetime
df.Date = pd.to_datetime(df.Date)

# extract values
x = df[df['Value']==True].sort_values(by='Date').head(1).Date

# groupby and plot
ax = df[df['Buy']==1].groupby('Date').size().plot(figsize=(7, 5), label='Buy')

# plot the vertical line; axvline works as long as x is one value
ax.axvline(x, color="red", linestyle="--", label='my value') 

# show the legend
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

enter image description here

软件包版本

import matplotlib as mpl

print(mpl.__version__)
print(pd.__version__)

[out]:
3.3.1
1.1.0