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


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 }}


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()

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

    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 }}


I think you should uncoment this line:


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')

    response = HttpResponse(content_type = 'image/png')
    canvas = FigureCanvasAgg(fig)
    return response


My setup:


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()
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 }}'>


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.


Leave a comment