|
| 1 | +""" |
| 2 | +This is an example that shows you how to work directly with the agg |
| 3 | +figure canvas to create a figure using the pythonic API. |
| 4 | +
|
| 5 | +In this example, the contents of the agg canvas are extracted to a |
| 6 | +string, which can in turn be passed off to PIL or put in a numeric |
| 7 | +array |
| 8 | +
|
| 9 | +
|
| 10 | +""" |
| 11 | +#!/usr/bin/env python |
| 12 | +from matplotlib.backends.backend_agg import FigureCanvasAgg |
| 13 | +from matplotlib.figure import Figure |
| 14 | +from matplotlib.axes import Subplot |
| 15 | +from matplotlib.mlab import normpdf |
| 16 | +from matplotlib.numerix import randn |
| 17 | + |
| 18 | +fig = Figure(figsize=(5,4), dpi=100) |
| 19 | +ax = fig.add_subplot(111) |
| 20 | + |
| 21 | +canvas = FigureCanvasAgg(fig) |
| 22 | + |
| 23 | +mu, sigma = 100, 15 |
| 24 | +x = mu + sigma*randn(10000) |
| 25 | + |
| 26 | +# the histogram of the data |
| 27 | +n, bins, patches = ax.hist(x, 50, normed=1) |
| 28 | + |
| 29 | +# add a 'best fit' line |
| 30 | +y = normpdf( bins, mu, sigma) |
| 31 | +line, = ax.plot(bins, y, 'r--') |
| 32 | +line.set_linewidth(1) |
| 33 | + |
| 34 | +ax.set_xlabel('Smarts') |
| 35 | +ax.set_ylabel('Probability') |
| 36 | +ax.set_title(r'$\rm{Histogram of IQ: }\mu=100, \sigma=15$') |
| 37 | + |
| 38 | +ax.set_xlim( (40, 160)) |
| 39 | +ax.set_ylim( (0, 0.03)) |
| 40 | + |
| 41 | +canvas.draw() |
| 42 | + |
| 43 | +s = canvas.tostring_rgb() # save this and convert to bitmap as needed |
| 44 | + |
| 45 | +# get the figure dimensions for creating bitmaps or numeric arrays, |
| 46 | +# etc. |
| 47 | +l,b,w,h = fig.bbox.get_bounds() |
| 48 | +w, h = int(w), int(h) |
| 49 | + |
| 50 | +if 0: |
| 51 | + # convert to a Numeric array |
| 52 | + X = fromstring(s, UInt8) |
| 53 | + X.shape = h, w, 3 |
| 54 | + |
| 55 | +if 0: |
| 56 | + # pass off to PIL |
| 57 | + import Image |
| 58 | + im = Image.fromstring( "RGB", (w,h), s) |
| 59 | + im.show() |
| 60 | + |
| 61 | + |
| 62 | + |
0 commit comments