Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Matplotlib in Django?

Tags:

From some examples from the Internet I made the test code below. It works!

... BUT if I reload the page, the pie will draw itself with the same image. Some parts get darker every time I reload the page. When I restart the the development server, it is reset. How do I draw properly with Matplotlib in Django? It looks like it remembers some drawings...

Source views.py (let urls.py link to it):

from pylab import figure, axes, pie, title from matplotlib.backends.backend_agg import FigureCanvasAgg  def test_matplotlib(request):     f = figure(1, figsize=(6,6))     ax = axes([0.1, 0.1, 0.8, 0.8])     labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'     fracs = [15,30,45, 10]     explode=(0, 0.05, 0, 0)     pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)     title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})      canvas = FigureCanvasAgg(f)         response = HttpResponse(content_type='image/png')     canvas.print_png(response)     return response 

I am using Django 1.0.1 and Python 2.6.2 (Linux).

like image 504
Jack Ha Avatar asked Dec 09 '09 15:12

Jack Ha


People also ask

Can I use matplotlib in Django?

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.

How does matplotlib work in Python?

matplotlib. pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

What is matplotlib used for?

Matplotlib is a cross-platform, data visualization and graphical plotting library for Python and its numerical extension NumPy. As such, it offers a viable open source alternative to MATLAB. Developers can also use matplotlib's APIs (Application Programming Interfaces) to embed plots in GUI applications.


1 Answers

You need to remove the num parameter from the figure constructor and close the figure when you're done with it.

import matplotlib.pyplot  def test_matplotlib(request):     f = figure(figsize=(6,6))     ....     matplotlib.pyplot.close(f) 

By removing the num parameter, you'll avoid using the same figure at the same time. This could happen if 2 browsers request the image at the same time. If this is not an issue, another possible solution is to use the clear method, i.e. f.clear().

like image 52
Cristian Ciupitu Avatar answered Oct 10 '22 00:10

Cristian Ciupitu