Tuesday, 21 March 2023

How to load Plotly graphs fast in a webpage?

I am using Django to create my first website. I have some complex plots made with Plotly which get passed to the render function as html (saved using to_html function). For example:

def sample_plot():
    import numpy as np
    import pandas as pd
    import plotly.graph_objects as go

    fig = go.Figure()

    fig.add_trace(go.Barpolar(
        r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
        name='11-14 m/s',
        marker_color='rgb(106,81,163)'
    ))
    fig.add_trace(go.Barpolar(
        r=[57.5, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5, 55.0],
        name='8-11 m/s',
        marker_color='rgb(158,154,200)'
    ))
    fig.add_trace(go.Barpolar(
        r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0],
        name='5-8 m/s',
        marker_color='rgb(203,201,226)'
    ))
    fig.add_trace(go.Barpolar(
        r=[20.0, 7.5, 15.0, 22.5, 2.5, 2.5, 12.5, 22.5],
        name='< 5 m/s',
        marker_color='rgb(242,240,247)'
    ))

    fig.update_traces(text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'])
    fig.update_layout(
        title='Wind Speed Distribution in Laurel, NE',
        font_size=16,
        legend_font_size=16,
        polar_radialaxis_ticksuffix='%',
        polar_angularaxis_rotation=90,

    )
    return fig.to_html(config={'displayModeBar': False})

Sample plot

This is rendered as follows:

sample_plot = sample_plot() 
context = {'plot':sample_plot, ... other stuff ... } 
return render(request, 'webpage.html', context)

Just passing this plot to the webpage (including it in context) increases loading time by 2.1 seconds (comparison using local server and same conditions). I have a few plots as complex as this one so the loading times make the webpage unusable.

Is this behaviour expected? Is there a better approach than using to_html to render the Plotly graphs? or is Plotly a non starter for webpage plots? Sorry if it is a basic mistake, it is my first website.

Loading times comparison



from How to load Plotly graphs fast in a webpage?

No comments:

Post a Comment