Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a Matplotlib plot in a Django web application?

I'm reading the book Matplotlib for Python Developers but am struggling to follow the example in the section "Matplotlib in a Django application" in chapter 8.

So far, I've issued the command

django-admin startproject mpldjango

and, in the mpldjango directory,

python manage.py startapp mpl

As per the example, in mpldjango/mpl I've made the views.py as follows:

import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np

def mplimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    x = np.arange(-2,1.5,.01)
    y = np.sin(np.exp(2*x))
    ax.plot(x, y)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

Next, the book says that the mpldjango/urls.py should have this line added to it:

urlpatterns = patterns('',
       (r'mplimage.png', 'mpl.views.mplimage'),
)

However, I don't see how this would work since in the 'default' urls.py, urlpatterns is a lits of django.conf.urls.url objects:

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

and there is no patterns constructor defined. Perhaps this book (which is from 2009) is referring to a legacy Django API? If so, how would I modify this code to make it work? (That is, after python manage.py runserver I should be able to browse to localhost:8000/mplimage.png and see an image of a chirped sinusoid).

like image 923
Kurt Peek Avatar asked Mar 09 '23 11:03

Kurt Peek


1 Answers

According to cannot import name patterns this is indeed a legacy interface of Django. I 'updated' it by making mpldjango/urls.py as follows:

from django.conf.urls import include, url
from django.contrib import admin
import mpl.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'mplimage.png', mpl.views.mplimage),
]

Now if I browse to http://localhost:8000/mplimage.png I see the plot as desired:

enter image description here

like image 178
Kurt Peek Avatar answered Mar 11 '23 04:03

Kurt Peek