[Fixed]-How to embed matplotlib graph in Django webpage?

24πŸ‘

I know this question is tagged as matplotlib, but I needed to do the same thing and I have found plotly to be easier to use and visually appealing as well. You can simply plot a graph and then in the view get the html code of the graph as :

# fig is plotly figure object and graph_div the html code for displaying the graph
graph_div = plotly.offline.plot(fig, auto_open = False, output_type="div")
# pass the div to the template

In the template do:

<div style="width:1000;height:100">
{{ graph_div|safe }}
</div>
πŸ‘€Deepak Saini

9πŸ‘

I searched quite a bit until I found a solution that worked for me when it comes to rendering a matplotlib image on a Django page. Often, simply a lengthy string was printed instead of a visualization being produced. So, what finally worked for me was the following:

First, the imports:

import matplotlib.pyplot as plt
from io import StringIO
import numpy as np

The dummy function returning a graphic is the following:

def return_graph():

    x = np.arange(0,np.pi*3,.1)
    y = np.sin(x)

    fig = plt.figure()
    plt.plot(x,y)

    imgdata = StringIO()
    fig.savefig(imgdata, format='svg')
    imgdata.seek(0)

    data = imgdata.getvalue()
    return data

This one can be called by some other function using and rendering the image returned by return_graph():

def home(request):
    context['graph'] = return_graph()
    return render(request, 'x/dashboard.html', context)

And in the dashboard.html file, the graphic is embedded by the following command:

{{ graph|safe }}
πŸ‘€Daniel B.

4πŸ‘

I think you should uncoment this line:

#canvas.print_png(response)

You can easily return plot using django HttpResponse instead using some extra libs. In the matplotlib there is a FigureCanvasAgg which gives you access to canvas where plot is rendered. Finaly you can simple return it as HttpResonse. Here you have very basic example.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg
from django.http import HttpResponse

def plot(request):
    # Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    fig, ax = plt.subplots()
    ax.plot(t, s)

    ax.set(xlabel='time (s)', ylabel='voltage (mV)',
           title='About as simple as it gets, folks')
    ax.grid()

    response = HttpResponse(content_type = 'image/png')
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(response)
    return response
πŸ‘€Janek

2πŸ‘

My setup:

Django==2.2.2
windrose==1.6.8

I am just sharing a solution I found online. I made it work with windrose and django (thanks to some article writer). And this

import base64
import io
from matplotlib import pyplot as plt

flike = io.BytesIO()
plt.savefig(flike)
b64 = base64.b64encode(flike.getvalue()).decode()
return render(request, template_name='details_wind.html', context={'wind_rose': wind_rose_image})

In the template, show it as an image:

<img src='data:image/png;base64,{{ wind_rose }}'>

0πŸ‘

If you want to embed matplotlib figures to django-admin you can try django-matplotlib field. This field doesn’t create a column in the database, but is rendered as a regular field. You don’t need to customize/subclass admin.ModelAdmin, just use this field in your models and define how the figure will be generated.

πŸ‘€bubble

Leave a comment