2

I currently have a Django project, with a view function, with code like the following (code copied from this post):

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

It creates a png from a graph and serves it directly. How can I make the background of the graph transparent in this png?

Community
  • 1
  • 1
Mads Skjern
  • 5,648
  • 6
  • 36
  • 40
  • 1
    What happens if you put after `f` the next code: `f.savefig('image.png', transparent=True)` – Victor Castillo Torres Aug 18 '13 at 19:02
  • Well, that saves the file with transparency alright. But I don't want to save it to a file, I want to generate the file and serve it directly. – Mads Skjern Aug 18 '13 at 20:06
  • possible duplicate of [How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)](http://stackoverflow.com/questions/14908576/how-to-remove-frame-from-matplotlib-pyplot-figure-vs-matplotlib-figure-frame) – tacaswell Aug 18 '13 at 20:18
  • Definitely _not_ a duplicate! Its not an issue with the figure. But in the process of saving to a png, the "empty background" is not saved as transparent (alphachannel in the png) but as grey. – Mads Skjern Aug 18 '13 at 20:35
  • Then see http://stackoverflow.com/questions/14088687/python-changing-plot-background-color-in-matplotlib and set the background color to `(0, 0, 0, 0)` – tacaswell Aug 18 '13 at 23:53

1 Answers1

0

Untested, but this should work. You don't have to write to an (actual) file, a file-like object should work. This code saves the image into the response.

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')
    f.savefig(response, transparent=True, format='png')
    #canvas.print_png(response)
    return response
John Lyon
  • 11,180
  • 4
  • 36
  • 44