PylonsHQ.

Layout: Fixed-width

Using matplotlib to output graphics from a controller

Skip to end of metadata
Go to start of metadata

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()

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

Powered by Pylons - Contact Administrators