Latest Version: 0.9.6.2
  Dashboard > Pylons Cookbook > ... > Recipes > Using matplotlib to output graphics from a controller
  Pylons Cookbook Log In | Sign Up   View a printable version of the current page.  
  Using matplotlib to output graphics from a controller
Added by Scott Torborg, last edited by Scott Torborg on Mar 28, 2008
Labels: 
(None)

Matplotlib can be used to output graphics directly from a controller, by writing to an intermediate StringIO object.

For example:

plot.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import logging

from plottest.lib.base import *

import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

from cStringIO import StringIO

log = logging.getLogger(__name__)

class PlotController(BaseController):

    def index(self):
        fig = Figure()
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(111)
        ax.plot([1, 4, 2, 3])
        
        s = StringIO()
        canvas.print_figure(s)
        response.headers['Content-Type'] = 'image/png'
        return s.getvalue()

Site running on a free Atlassian Confluence Open Source Project License granted to Pylons. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.3.3 Build:#645 Feb 13, 2007) - Bug/feature request - Contact Administrators
Top