dynamically generated matplotlib images via django

I finally figured out how to serve a dynamically generated matplotlib image through Django. Here is the necessary views.py and urls.py code for an example case:

views.py

from django.http import HttpResponse

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import matplotlib.pyplot as plt
import numpy as np

def index(request):
    x = np.random.randn(100000)
    f = plt.figure(111)
    plt.hist(x, color='lightblue')
    plt.xlabel('X')
    plt.ylabel('Frequency')
    plt.title('Histogram of Randomly Generated Values')
    canvas = FigureCanvas(f)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    plt.close()
    return response

urls.py

from django.conf.urls import patterns, url

from histogram import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index')
)

Result

histogram_in_browser

Post Author: badassdatascience

Leave a Reply

Your email address will not be published.