Plot.ly does not work when called from a function

Hi all,

I have a file plotting.py where I defined couple of functions to plot some graphs. When I call one of the functions in ipython notebook, nothing happens. When I copy the exact code and execute it in the ipython, it works.

This is an example function:

import plotly.graph_objs as go
import plotly.plotly as py
def display_test():
    import plotly.graph_objs as go
    import plotly.plotly as py
    trace0 = go.Scatter(
              x=[1, 2, 3, 4],
              y=[10, 15, 13, 17]
    )
    trace1 = go.Scatter(
      x=[1, 2, 3, 4],
      y=[16, 5, 11, 9]
    )
    data = go.Data([trace0, trace1])
    py.iplot(data, filename = 'basic-line')

I am not using the offline ipython mode.

When I use at the last line py.plot(data, filename = 'basic-line'), I get opened the figure in the plot.ly webpage. That works from both the function and directly from the code. But I want to display the figure as an output of a notebook cell.

Btw. what is the best of sharing the notebooks with plot.ly graphs? When I use the notebook in the offline mode and use http://nbviewer.jupyter.org/ to view it, the plot.ly graphs are not showed. That’s actually why I am using it in the ‘real-time’ mode.

Thank you for help!

1 Like

Hi lopyslav,
Unfortunate that there is no reply yet to this question.
I am currently having the same problem.
Did you in the meanwhile find a solution to this problem? Would be grateful if you could share your updates!

No, I havent. I am sorry.

@lopyslav @rrighart @1900wi
In order to use a wrapper function for defining, and iplot-ting a Plotly figure, replace the line
py.iplot(data, filename = 'basic-line')
in the lopyslav’s code with

return py.iplot(data, filename = 'basic-line')

1 Like

Thank you empet, that works like a charm!
For those using Python 3: return(py.iplot(data, filename = 'basic-line'))

@empet @rrighart @lopyslav Hi to all I’m trying to do the same thing , But I have two .py files one where I defined the funcion and another .py file where I call this function and where also I pass the x and y axis information.
In other words, I wanted to reuse the code that assembles the graph using it as a function and assembling several graphs with the same code just change the x and y info.

Hello Guys

My problem for Jupyter Notebook solved in this way:

   import plotly.express as _plt
   from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
   
   def plotWly():

          fig = _plt.area(Df)

          return iplot(fig)

Maybe be helpful for some other guys!