Plotly iplot()不在函数内运行

时间:2018-03-14 12:18:51

标签: python-3.x jupyter-notebook plotly jupyter

我正在尝试在Jupyter中的函数中使用iplot(),以便我可以在图上使用过滤器并使其动态更改。代码本身就像一个单元格一样工作

 # Code for put by ticker
 data = []
 opPriceDic = priceToArray(getPuts(getOptionPricesByTicker('ABBV')))
 for key, values in opPriceDic.items():
    trace = go.Scatter(
       x = numberOfDays,
       y = values,
       name = 'option',
       line = dict(
           width = 4)
       )
       data.append(trace)
# Edit the layout
layout = dict(title = 'Call prices for ' ,
          xaxis = dict(title = 'Days to Expiration'),
          yaxis = dict(title = 'Price '),
          )
fig = dict(data=data, layout=layout)
py.iplot(fig, filename='calls For ')

但是一旦将其置于函数中,图形就无法加载

def graph(ticker):    
# Code for put by ticker
data = []
opPriceDic = priceToArray(getPuts(getOptionPricesByTicker(ticker)))
for key, values in opPriceDic.items():
    trace = go.Scatter(
        x = numberOfDays,
        y = values,
        name = 'option',
        line = dict(
            width = 4)
    )
    data.append(trace)
# Edit the layout
layout = dict(title = 'Call prices for ' ,
              xaxis = dict(title = 'Days to Expiration'),
              yaxis = dict(title = 'Price '),
              )
fig = dict(data=data, layout=layout)
py.iplot(fig, filename='calls For ')

但是如果我将iplot()更改为plot(),它会调用pl​​otly API并打开一个显示图形的新选项卡。

我只是想知道是否有人之前已经注意到这一点并且可能遇到了解决方案?

(如果我在错误的区域,我会删除帖子)

1 个答案:

答案 0 :(得分:0)

我尝试使用熊猫data.reader调用在开始日期和结束日期之间提取报价数据。 data.reader似乎可以在函数中使用。在问题代码中,如果opPriceDic字典可以转换为数据框,则iplot()可以在不使用布局和无花果的情况下对其进行绘制,如下所示:

# Import libraries
import datetime
from datetime import date
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline

import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot 
init_notebook_mode(connected=True)

init_notebook_mode(connected=True)
cf.go_offline()


# Create function that uses data.reader and iplot()
def graph(ticker):
    # create sample data set
    start = datetime.datetime(2006, 1, 1)
    end = datetime.datetime(2016, 1, 1)
    df = data.DataReader(ticker, 'morningstar', start, end)
        df = df.reset_index() 
        df['numberOfDays'] = df.apply(lambda x: abs((datetime.datetime.now() - x['Date']).days), axis=1)

# call iplot within the function graph()
df.iplot(kind='line', x='numberOfDays', y='Close', xTitle='Days', yTitle='Value', title='Prices', width=4)

Line plot using iplot() from within a function