How to set config in Plotly without using fig.show()

Hello I am trying to display a plotly chart with some custom configuration. All of the code examples from Plotly show setting configurations within the fig.show() method which results in VIKTOR opening a new tab which shows the plot by itself.

Below is the code i am using which is based on a snippet from the plotly website here:

   @PlotlyView("Plotly view", duration_guess=1)
   def get_plotly_view(self, params, **kwargs):
       df = data.stocks()

       fig = go.Figure(
           data=go.Scatter(
               x=df.date,
               y=df.GOOG,
           ),
           layout=go.Layout(
               yaxis=dict(title="Price in USD"),
               newshape=dict(label=dict(texttemplate="Change: %{dy:.2f}")),
               title="Google Share Price 2018/2019",
           ),
       )

       fig.show(
           config={
               "modeBarButtonsToAdd": [
                   "drawline",
               ]
           }
       )

       return PlotlyResult(fig)

Hi Ian,

Welcome to the community! And thank you for your question. As can be seen in our documentation, rather than using the show method, you should extract the json by using fig.to_json(), and then adding the json to the PlotlyResult. E.g.

   @PlotlyView("Plotly view", duration_guess=1)
   def get_plotly_view(self, params, **kwargs):
       df = data.stocks()

       fig = go.Figure(
           data=go.Scatter(
               x=df.date,
               y=df.GOOG,
           ),
           layout=go.Layout(
               yaxis=dict(title="Price in USD"),
               newshape=dict(label=dict(texttemplate="Change: %{dy:.2f}")),
               title="Google Share Price 2018/2019",
           ),
       )

       return PlotlyResult(fig.to_json())

As always seems to be the case asking for advice gives me clarity and I find the solution! Putting the solution here in case anyone else has the same problem. Fixed it with update_layout method as below:

    @PlotlyView("Plotly view", duration_guess=1)
    def get_plotly_view(self, params, **kwargs):
        df = data.stocks()

        fig = go.Figure(
            data=go.Scatter(
                x=df.date,
                y=df.GOOG,
            ),
            layout=go.Layout(
                yaxis=dict(title="Price in USD"),
                newshape=dict(label=dict(texttemplate="Change: %{dy:.2f}")),
                title="Google Share Price 2018/2019",
            ),
        )

        fig.update_layout(
            modebar={'add': 'drawline'}
        )

        return PlotlyResult(fig.to_json())

Thanks mslootweg I found the to_json method but couldn’t see how to set configuration to the toolbar on plotly. Found i had to set the options through update_layout().

1 Like