Figure Matplotlib avec Django
urls.py
url(r'^_Matplotlib/Bar/$', 'visualization.views.GraphsViewBar'),
views.py

# -*- coding: utf-8 -*-from django.shortcuts import render_to_responsefrom django.template import RequestContextfrom django.http import HttpResponseRedirectfrom wiki.models import Article, ArticleRevision, URLPathfrom django.http import HttpResponsefrom matplotlib.backends.backend_agg import FigureCanvasAggimport matplotlib.pyplotimport matplotlib.pyplot as pltimport numpy as npdef GraphsViewBar(request):f = plt.figure()x = np.arange(10)h = [0,1,2,3,5,6,4,2,1,0]plt.title('Title')plt.xlim(0, 10)plt.ylim(0, 8)plt.xlabel('x label')plt.ylabel('y label')bar1 = plt.bar(x,h,width=1.0,bottom=0,color='Green',alpha=0.65,label='Legend')plt.legend()canvas = FigureCanvasAgg(f)response = HttpResponse(content_type='image/png')canvas.print_png(response)matplotlib.pyplot.close(f)return response
Figure Matplotlib dans une page HTML
urls.py
url(r'^_Matplotlib/$', 'visualization.views.GraphsView'),url(r'^_Matplotlib/Bar/$', 'visualization.views.GraphsViewBar'),
mian.html
<img src="http://127.0.0.1:8000/_Matplotlib/Bar/" />
views.py

# -*- coding: utf-8 -*-from django.shortcuts import render_to_responsefrom django.template import RequestContextfrom django.http import HttpResponseRedirectfrom wiki.models import Article, ArticleRevision, URLPathfrom django.http import HttpResponsefrom matplotlib.backends.backend_agg import FigureCanvasAggimport matplotlib.pyplotimport matplotlib.pyplot as pltimport numpy as npdef GraphsView(request):return render_to_response("visualization/main.html", context_instance=RequestContext(request))def GraphsViewBar(request):f = plt.figure()x = np.arange(10)h = [0,1,2,3,5,6,4,2,1,0]plt.title('Title')plt.xlim(0, 10)plt.ylim(0, 8)plt.xlabel('x label')plt.ylabel('y label')bar1 = plt.bar(x,h,width=1.0,bottom=0,color='Green',alpha=0.65,label='Legend')plt.legend()canvas = FigureCanvasAgg(f)response = HttpResponse(content_type='image/png')canvas.print_png(response)matplotlib.pyplot.close(f)return response
Exemples d'erreurs Matplotlib avec Django (Centos)
Premiere étape, installer matplotlib sur le serveur:
yum install python-matplotlib

Dans cette section on va voir les erreurs que l'on peut obtenir quand on cherche à utiliser matplotlib en déployant une application développée avec Django. L'erreur la plus courante est surement la suivante:
Failed to create /root/.matplotlib; consider setting MPLCONFIGDIR to a writable directory for matplotlib configuration data
L'explication est simple, par défaut Matplotlib est configuré pour travailler avec un GUI et essaye d'ouvrir une connexion avec X11 (voir les articles: Matplotlib in a web application server et What is a backend). Pour empêcher cela, voici la solution
import tempfileos.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()# do this before importing pylab or pyplotimport matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as plt

Une autre erreur est la suivante:
error: Gtk* backend requires pygtk to be installed
Dans ce cas cela signifie simplement que Gtk n'est pas installé sur votre serveur. La solution est donc tout simplement d'installer Gtk comme ceci:
yum install pygtk2
Ces deux erreurs sont les plus importantes, après il peut survenir d'autres problèmes, par exemple avec l'utilisation de LaTeX pour écrire du texte qui peut mal fonctionner, dans ce cas la solution est souvent d'ajouter la ligne suivante:
plt.rcParams['mathtext.fontset'] = "stix"
avant d'utiliser LaTeX.
