【问题标题】:Plotting security vs time traded with Python用 Python 绘制安全性与交易时间的关系图
【发布时间】:2016-05-05 14:07:22
【问题描述】:

我有一个数据框,其中包含许多代表证券的列,索引的时间从 00:00 到 23:55(每行间隔 5 分钟),每个单元格都有 1 或 0 . 我想绘制某种形式的箱线图,它可以可视化类似于我在这里绘制的数据:

但是我很困惑,因为我所拥有的都是二进制值,并且在绘制时间时不能使用它们。我仅限于使用 pandas 和 matplotlib。

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

一种方法可能是使用我在上面评论过的链接,尽管您的初始数据集不同。该过程包括为每列分配数值并将零更改为NaN,如下所示:

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("testdata.txt",parse_dates=0,index_col=0)
df = df.applymap(lambda x:x if x else pd.np.nan)
for n, col in enumerate(df.columns): df[col] = df[col]*n
df.plot(lw=10,legend=False)
plt.yticks(pd.np.arange(len(df.columns)), df.columns)
plt.tight_layout()
plt.show()

结果数据框是:

                     A   B   C    D  E
time                                  
2016-05-05 00:00:00  0 NaN NaN  NaN  4
2016-05-05 00:05:00  0 NaN NaN  3.0  4
2016-05-05 00:10:00  0 NaN NaN  3.0  4
2016-05-05 00:15:00  0 NaN NaN  3.0  4

还有剧情:

问候。

【讨论】:

    【解决方案2】:

    我认为您可以使用 matplotlib 中损坏的条形图。文档是here

    这是我测试的一个简单版本: 不幸的是,我想不出一种方法来通过权益向量化操作。

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    
    df = pd.DataFrame()
    df['qqq'] = [1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0,0]
    df['dia'] = [0,0,1,1,0,1,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1,1,1,1,1]
    
    ones = []
    for col in df.columns:
        one = df[df[col].diff() != 0][:][col]
        one = one[one == 1]
        ones.append(one)
    
    hranges = []
    for col in df.columns:
        diff = df[df[col].diff() != 0]
        spread = pd.DataFrame(diff[col].index, columns=[col])
        spread = spread.set_value(len(spread), col, len(df[col].index))
        spread = spread.diff(periods=-1).fillna(spread[pd.isnull(spread.diff()) == True])*-1
        spread = spread.drop(spread.index[-1])
        re_index = pd.DataFrame(df[df[col].diff() != 0][:][col].tolist())
        re_index = re_index[re_index[0] == 0]
        hranges.append(spread.drop(re_index[re_index[0] == 0].index))
        hranges[j].columns = ['width']
        hranges[j]['hval'] = ones[j].index.tolist()
        cols = hranges[j].columns
        cols = cols[-1:] | cols [:-1]
        hranges[j] = hranges[j][cols]
        j += 1
    
    vals = []
    for j in range(len(hranges)):    
        val = [(hranges[j].hval[i], hranges[j].width[i]) for i in hranges[j].index]
        vals.append(val)
    
    fig, ax = plt.subplots()
    j = 0
    for col in df.columns:
        ax.broken_barh(vals[j], ((j+1)*10,10))
        j += 1
    ax.set_yticks([((k+1) * 10) + 5 for k in range(j)])
    ax.set_yticklabels(df.columns)    
    plt.show()
    

    结果如下:

    显然,您的示例将具有 x 轴的时间值,但我想您可以弄清楚。

    【讨论】:

      猜你喜欢
      • 2019-06-09
      • 2018-11-14
      • 2012-07-29
      • 1970-01-01
      • 2015-11-17
      • 2019-12-03
      • 1970-01-01
      • 2015-04-17
      • 2018-09-02
      相关资源
      最近更新 更多