Plotly.py: FigureWidget does work not from inside an if statement

Created on 3 Nov 2019  ·  7Comments  ·  Source: plotly/plotly.py

Encountered in Jupyter Lab.

Take the following 2 cases:

fig = go.FigureWidget()
fig

&

silent=False

if not silent:
    fig = go.FigureWidget()
    fig

The first one produces a figure, the second one does not.
Why don't they behave similarly?

If I use the @interact decorator in the second case.
e.g.

if not silent:
    fig = go.FigureWidget()
    fig.add_scatter()

    @interact(s=(3,5))
    def update(s=3):
        with fig.batch_update():
            fig.data[0].y = np.random.normal(size=s)
    fig

the slider appears, but the figure does not.

All 7 comments

The way widgets work is that they render if they are the “output” of a cell, i.e. the last statement.

For @interact to work, the widget must be returned from the function.

@nicolaskruchten I undestand that it currently works like that. But, for the future, is there a reason for the widget not to work when returned from the if statement? An instance created with go.Figure() does.

if statements don't actually return anything, no. For a normal go.Figure() to work within an if statement you must call fig.show() on it.

These limitations aren't really Plotly limitations but rather Jupyter/Python limitations that we can't do much about :)

For example, this doesn't render anything, as expected:

image

You may be able to use the display command:

if True:
    fig = go.Figure()
    display(fig)

(if you have an older version of ipython, you may need to import it: from IPython.display import display

TIL about display :)

Thanks a lot!

display is what IPython calls automatically on the last top-level expression to display it in your first example.

Was this page helpful?
0 / 5 - 0 ratings