在y轴上绘制体积的时间序列,在x轴上绘制年份+周数,其类型由色相决定

时间:2019-05-23 02:18:28

标签: python-3.x pandas numpy matplotlib seaborn

导入库

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib as mpl
import seaborn as sns
from datetime import datetime
%matplotlib inline
import warnings; warnings.filterwarnings(action='once')

导入数据

df = pd.read_excel("CDS Detail - 2019 05 22 - sample.xlsx")

检查数据格式

df.head()
Date                Status  Method  Volume
2018-05-10 20:45:28 F   Discretionary   1
2018-05-03 21:09:10 F   Discretionary   1
2018-05-17 14:19:47 F   Discretionary   1
2018-05-17 14:21:17 F   Discretionary   1
2018-05-17 14:19:47 F   Discretionary   1

删除空值

df = df[df['Date'].notnull()]

检查类型

df.columns
Index(['Status', 'Method', 'Volume', 'Date'], dtype='object')
df.dtypes
Status            object
Method            object
Volume             int64
Date      datetime64[ns]
dtype: object

查看数据标题

df.head()
Status  Method  Volume  Date
0   F   Discretionary   1   2018-05-10 20:45:28
1   F   Discretionary   1   2018-05-03 21:09:10
2   F   Discretionary   1   2018-05-17 14:19:47
3   F   Discretionary   1   2018-05-17 14:21:17
4   F   Discretionary   1   2018-05-17 14:19:47

使用datetime64作为索引重置轴

df = df.set_index('Date')

df.head()
Status  Method  Volume
Date            
2018-05-10 20:45:28 F   Discretionary   1
2018-05-03 21:09:10 F   Discretionary   1
2018-05-17 14:19:47 F   Discretionary   1
2018-05-17 14:21:17 F   Discretionary   1
2018-05-17 14:19:47 F   Discretionary   1

weekly = df.resample(rule='W').sum()

确认数据已按周重新采样。请注意缺少的“方法”功能

weekly
Date        Volume
2018-04-08  7
2018-04-15  10
2018-04-22  40
2018-04-29  69
2018-05-06  128
2018-05-13  380
2018-05-20  464
2018-05-27  6052
2018-06-03  6095
2018-06-10  6224
2018-06-17  3084
2018-06-24  5

用于检查数据的基本matplotlib图表将以每周交易量weekly.plot()的形式图表

现在我们如何添加“方法”作为图例以为每个方法类创建带有行的线图?

这就是我被困住的地方。如何使用这种样式将x轴作为日期,将y轴作为体积,为每个“方法”绘制多行?

sns.lineplot(data = weekly, hue = 'Method')

1 个答案:

答案 0 :(得分:0)

您可能在x通话中缺少ylineplot。尝试此操作而不重置索引。

sns.lineplot(data = weekly,  x='Date', y='Volume', hue = 'Method')

在此处查看示例:https://seaborn.pydata.org/generated/seaborn.lineplot.html