多个matplotlib子图:将熊猫数据框HTML与每个子图交错

时间:2018-11-21 22:51:10

标签: python pandas matplotlib jupyter-notebook

我有一个pandas.DataFrame多行(我要检查的每笔交易1行)

trades = pandas.read_csv(...)

我想在matplotlib子图中绘制每笔交易。我使用pyplot.figure创建了一个len(trades),以创建足够的高度

fig = pyplot.figure(figsize=(40,15 * len(trades)))

然后我遍历每笔交易并生成一个图

for i,r in enumerate(trades.iterrows()):
    _, trade = r

    start = trade.open_time  - datetime.timedelta(seconds=30)
    end   = trade.close_time + datetime.timedelta(seconds=30) 

    b = bids[start:end]
    a = asks[start:end]

    ax = fig.add_subplot(len(trades),1,i+1)

    # plot bid/ask
    ax.plot_date(b.index, b, fmt='-',  label='bid')
    ax.plot_date(a.index, a, fmt='-',  label='ask')

    # plot entry/exit markers
    ax.plot(trade.open_time,  trade.open_price,  marker='o', color='b')
    ax.plot(trade.close_time, trade.close_price, marker='o', color='r')

    ax.set_title("Trade {}".format(i+1, fontsize=10)
    ax.set_xlabel("Date")
    ax.set_ylabel("Price")

    ax.legend(loc='best', fontsize='large')

pyplot.show()

# free resources
pyplot.close(fig.number) 

这很好用。

但是,现在,我想显示有关交易的数据框的渲染HTML。

由于我是在Jupyter笔记本中进行此操作的,因此我可以从this SO answer中找到以下代码段,这些代码段将以html格式显示数据框:

t = pandas.DataFrame(trades.iloc[i]).T
IPython.display.display(IPython.display.HTML(t.to_html())

我将此代码段插入循环中。

问题在于,每笔交易的渲染HTML数据框都是一个接一个地打印的,然后在所有数据框都打印完之后,打印图。

+-----------+
| dataframe |
+-----------+
+-----------+
| dataframe |
+-----------+
+-----------+
| dataframe |
+-----------+
+------+
|      |
| plot |
|      |
+------+
+------+
|      |
| plot |
|      |
+------+
+------+
|      |
| plot |
|      |
+------+

鉴于我已经创建了一个大的pyplot.figure,并且在循环后调用了pyplot.show(),这很有意义-在循环中,我输出数据帧HTML,然后循环显示图。

问题:

如何交错笔记本HTML和每个子图?

+-----------+
| dataframe |
+-----------+
+------+
|      |
| plot |
|      |
+------+
+-----------+
| dataframe |
+-----------+
+------+
|      |
| plot |
|      |
+------+
+-----------+
| dataframe |
+-----------+
+------+
|      |
| plot |
|      |
+------+

1 个答案:

答案 0 :(得分:1)

我相信您需要创建三个单独的图形并在循环中调用plt.show()。这样的事情(注意,我不需要使用Jupyter笔记本前端pyplot.close {em} ):

trades = pandas.read_csv(...)

for i, r in enumerate(trades.iterrows()):
    _, trade = r

    start = trade.open_time  - datetime.timedelta(seconds=30)
    end   = trade.close_time + datetime.timedelta(seconds=30) 

    b = bids[start:end]
    a = asks[start:end]

    fig, ax = plt.subplots(figsize=(40, 15))

    # plot bid/ask
    ax.plot_date(b.index, b, fmt='-',  label='bid')
    ax.plot_date(a.index, a, fmt='-',  label='ask')

    # plot entry/exit markers
    ax.plot(trade.open_time,  trade.open_price,  marker='o', color='b')
    ax.plot(trade.close_time, trade.close_price, marker='o', color='r')

    ax.set_title("Trade {}".format(i+1, fontsize=10))
    ax.set_xlabel("Date")
    ax.set_ylabel("Price")

    ax.legend(loc='best', fontsize='large')

    t = pandas.DataFrame(trades.iloc[i]).T
    IPython.display.display(IPython.display.HTML(t.to_html())

    pyplot.show()