On Sat, Jul 23, 2011 at 2:53 PM, robert rottermann <robert.rottermann@gmx.ch> wrote:
thanks ben,
(sorry for sending answer twice)

> When you call savefig(), you can pass it the kwarg option of
> bbox_inches='tight' and that should help get rid of any extra area you
> may have.
> Ben Root
I tried to follow your advice. however it did not help. This is what I do:

- get the current figure with gcf.
- read an image from a file with imread
- save it to the canvas with imsave
- hide the axes
- call fig.savefig('out.svg', transparent=True, bbox_inches='tight',

then I create a PIL Image and return it to the calling web server.

The image is displayed with a fat (1.5 cm) gray border which I do not want.

thanks for any further intelligence


here is my code cleansed of irrelevant parts

# supporting method creating the plot
def makeHlwdChart(self, values = ['a', 'd', 'e', 'f', 'b']):
    # get current axes object
    frame1 = plt.gca()
    # get current figure
    fig = plt.gcf()
    # read the image file
    pic = plt.imread(imp_path)
    # the picture is upside down so rotate and fip it
    pic = np.fliplr(np.rot90(pic, k=2))
    # draw it on the canvas
    plt.imshow(pic, figure=fig)
    # hide axes

    fig.savefig('out.svg', transparent=True, bbox_inches='tight',

    return pic

# method called from the web server
def __call__(self, w=300, h=300, default_format = 'PNG', set_headers=False):
    # lock graphics
    # we don't want different threads to write on each other's canvases,
    # make sure we have a new one
    # makeHlwdChart draws on the canvas, so we do not need its return value
    makeHlwdChart(self, values)
    canvas = pylab.get_current_fig_manager().canvas
    imageSize = canvas.get_width_height()
    imageRgb = canvas.tostring_rgb()
    img = Image.fromstring("RGB", imageSize, imageRgb)
    #size = int(w), int(h)
    #img.thumbnail(size, Image.ANTIALIAS)
    format = img.format and img.format or default_format
    thumbnail_file = StringIO()
    ## quality parameter doesn't affect lossless formats
    img.save(thumbnail_file, format, quality=88)
    if set_headers:
        self.request.RESPONSE.setHeader('Pragma', 'no-cache')
        self.request.RESPONSE.setHeader('Content-Type', 'image/%s' %

    # unlock graphics

    return thumbnail_file.getvalue()

Does the image look correct if you save it as a PNG file?  It might be a problem with the SVG backend.   Also, which version of matplotlib are you using.  There was a lot of work on the bbox_inches stuff and this problem might have already been fixed.

Ben Root