Search code examples
pythonplotlypy-shiny

How to pass config options to plotly in Shiny for Python?


How do I configure a plotly graph in shiny for Python?

Consider the following minimal shiny example.

from shiny import ui, App 
from shinywidgets import output_widget, render_widget
import plotly.express as px
import plotly.graph_objects as go

app_ui = ui.page_fluid(
    output_widget("plotly")
)

def server(input, output, session):
    @render_widget
    def plotly():
        df = px.data.gapminder().query("country=='Canada'")
        fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
        return go.FigureWidget(fig)

app = App(app_ui, server)

How do I set the config = {'displayModeBar': False}.

I cannot use fig.show(config=config) as this opens a seperate tab with just the plotly graph.

@render_widget and go.FigureWidget() also do not seem to be able to accept the option.

All online resources point to using fig.show(), which I cannot use in shiny for Python. Using fig.show(config=config) opens a seperate tab with just the plotly graph. I have searched the internet, but I have not come yet to a workaround.

In R, I can just add the config to the fig object.

Why is this not the case in Python?


Solution

  • This is a limitation of FigureWidget, see e.g. the comment in posit-dev/py-shiny#944. However, there exists a workaround described in plotly/plotly.py#1074 which says how you can pass an option to the FigureWidget. Essentially, one can make use of the merge operator | introduced in Python 3.9 and write

    fig = go.FigureWidget()
    fig._config = fig._config | {'displayModeBar': False}
    

    Your example could be written like this:

    from shiny import ui, App 
    from shinywidgets import output_widget, render_widget
    import plotly.express as px
    import plotly.graph_objects as go
    
    app_ui = ui.page_fluid(
        output_widget("plotly")
    )
    
    def server(input, output, session):
        @render_widget
        def plotly():
            df = px.data.gapminder().query("country=='Canada'")
            fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
            fig = go.FigureWidget(fig)
            fig._config = fig._config | {'displayModeBar': False}
            return fig
    
    app = App(app_ui, server)
    

    And then the modebar disappears:

    enter image description here