Django和matplotlib的透明pngs

时间:2013-08-18 18:41:06

标签: django matplotlib

我目前有一个带有视图功能的Django项目,代码如下(从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

它从图形创建一个png并直接提供它。如何在此png中使图表的背景透明?

1 个答案:

答案 0 :(得分:0)

未经测试,但这应该有用。您不必写入(实际)文件,类文件对象应该工作。此代码将图像保存到响应中。

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