【问题标题】:Plot timeseries of volume on the y-axis and year + week number on the x-axis with type determined by hue在 y 轴上绘制时间序列,在 x 轴上绘制年份 + 周数,类型由色调确定
【发布时间】:2019-05-23 02:18:27
【问题描述】:

导入库

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')

【问题讨论】:

  • 请添加一个示例数据集以及您到目前为止尝试过的内容
  • @Gio 根据您的 cmets 更新了帖子。感谢我的帮助,因为我是 Stackoverflow 的新手。任何反馈表示赞赏。

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


【解决方案1】:

您可能在lineplot 电话中缺少xy。在不重置索引的情况下试试这个。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多