RuntimeError转换Matplotlib到Plotly

时间:2019-01-30 21:38:17

标签: python matplotlib plotly

使用matplotlib语法在使用Plotly进行绘图时遇到麻烦。该matplotlib代码工作正常,当我尝试使用Plotly根据自己的文档,我得到错误试图运行:https://plot.ly/matplotlib/getting-started/

代码:

def analyze(context=None, perf=None):
    end = time.time()
    log.info('elapsed time: {}'.format(timedelta(seconds=end - context.start_time)))

    import matplotlib
    matplotlib.use('tkagg')

    import matplotlib.pyplot as plt
    import plotly.plotly as py
    mpl_fig = plt.figure()
    # The quote currency of the algo exchange
    quote_currency = list(context.exchanges.values())[0].quote_currency.upper()

    # First chart: Portfolio Value. Plot the portfolio value over time.
    ax1 = plt.subplot(611)
    perf.loc[:, 'portfolio_value'].plot(ax=ax1)
    ax1.set_ylabel('Portfolio\nValue\n({})'.format(quote_currency))

    # Second chart: Asset price. Plot the price increase or decrease over time.
    ax2 = plt.subplot(612, sharex=ax1)
    perf.loc[:, 'close_price'].plot(ax=ax2, label='Price')

    ax2.set_ylabel('{asset}\n({quote})'.format(
        asset=context.market.symbol, quote=quote_currency
    ))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index.floor('1 min'), 'close_price'],
            marker='^',
            s=100,
            c='green',
            label=''
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index.floor('1 min'), 'close_price'],
            marker='v',
            s=100,
            c='red',
            label=''
        )

    # Third chart: Cash. Plot our cash
    ax4 = plt.subplot(613, sharex=ax1)
    perf.loc[:, 'cash'].plot(
        ax=ax4, label='Quote Currency ({})'.format(quote_currency)
    )
    ax4.set_ylabel('Cash Flow\n({})'.format(quote_currency))

    perf['algorithm'] = perf.loc[:, 'algorithm_period_return']

    # Fourth chart: Performance vs Holding. Plot algorithm performance against holding asset
    ax5 = plt.subplot(614, sharex=ax1)
    perf.loc[:, ['algorithm', 'price_change']].plot(ax=ax5)
    ax5.set_ylabel('Performance\nvs Hold')

    # Fifth charg: RSI. Plot RSI over time period.
    ax6 = plt.subplot(615, sharex=ax1)
    perf.loc[:, 'rsi'].plot(ax=ax6, label='RSI')
    ax6.set_ylabel('RSI')
    ax6.axhline(context.RSI_OVERBOUGHT, color='darkgoldenrod')
    ax6.axhline(context.RSI_OVERSOLD, color='darkgoldenrod')

    if not transaction_df.empty:
        ax6.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index.floor('1 min'), 'rsi'],
            marker='^',
            s=100,
            c='green',
            label=''
        )
        ax6.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index.floor('1 min'), 'rsi'],
            marker='v',
            s=100,
            c='red',
            label=''
        )
    plt.legend(loc=3)
    start, end = ax6.get_ylim()
    ax6.yaxis.set_ticks(np.arange(0, end, end / 5))

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()
    timestr = time.strftime('%Y-%m-%d')
    unique_url = py.plot_mpl(mpl_fig, filename=timestr, fileopt='new')
    pass

我为Plotly添加的代码(我在不使用'tkagg'的情况下遇到了相同的问题):

import matplotlib
matplotlib.use('tkagg')

import matplotlib.pyplot as plt
import plotly.plotly as py
mpl_fig = plt.figure()

timestr = time.strftime('%Y-%m-%d')
unique_url = py.plot_mpl(mpl_fig, filename=timestr, fileopt='new')

错误:

    raise RuntimeError('Cannot get window extent w/o renderer')

RuntimeError: Cannot get window extent w/o renderer

遵循此线程中的指示:Seaborn matplotlib: Cannot get window extent w/o renderer (RuntimeError)

0 个答案:

没有答案