How to use Plotly Express in your Django project

Plotly Express is a terse, consistent, high-level API for creating figures. If you are plotting data from your models.py you may follow the below steps:

Step 1

pip3 install plotly

Step 2

import plotly.express as px

Step 3

If you are using a class based view after setting your template_name and queryset  you can use the below code without creating a function. If not you will have to go with a function based view with the below code.

set_variable = YOURMODELNAME.objects.all()
    set_x_y_initial_variable = [
        {'crop': x.crop,
         'hectares': x.hectares,
         } for x in set_variable
    ]

    df = pd.DataFrame(set_x_y_initial_variable)
    
    fig = px.line(df, x='crop', y='hectares', width=600, height=300, title="Most cultivated crops in Ghana "
                                            "by hectares", template='seaborn', color_discrete_sequence=['forestgreen'])
    fig.update_layout({
        'plot_bgcolor': 'rgba(0, 0, 0, 0)',
        'paper_bgcolor': 'rgba(0, 0, 0, 0)',
    })
    bar_plot = plot(fig, output_type='div')

NB: In your get_context_data, set your context like below, that's if you're using CBV, else just render the html and pass the plot as the context data.

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['crops_cultivated'] = self.bar_plot
        return context

Step 5

In your html file turn off autoescape or just use the safe function to display your plot.

{% autoescape off %}
{{crops_cultivated}}
{% endautoescape %}

or simply

{{crops_cultivated|safe}}

 

If you need assistance with your projects feel free to email me at info@airgad.com or whatsapp Jesse stay safe!