Returning Matplotlib image as string

前端 未结 4 1901
天命终不由人
天命终不由人 2020-12-31 12:14

I am using matplotlib in a django app and would like to directly return the rendered image. So far I can go plt.savefig(...), then return the location of the im

4条回答
  •  情话喂你
    2020-12-31 12:41

    There is a recipe in the Matplotlib Cookbook that does exactly this. At its core, it looks like:

    def simple(request):
        from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
        from matplotlib.figure import Figure
    
        fig=Figure()
        ax=fig.add_subplot(111)
        ax.plot(range(10), range(10), '-')
        canvas=FigureCanvas(fig)
        response=django.http.HttpResponse(content_type='image/png')
        canvas.print_png(response)
        return response
    

    Put that in your views file, point your URL to it, and you're off and running.

    Edit: As noted, this is a simplified version of a recipe in the cookbook. However, it looks like there is a difference between calling print_png and savefig, at least in the initial test that I did. Calling fig.savefig(response, format='png') gave an image with that was larger and had a white background, while the original canvas.print_png(response) gave a slightly smaller image with a grey background. So, I would replace the last few lines above with:

        canvas=FigureCanvas(fig)
        response=django.http.HttpResponse(content_type='image/png')
        fig.savefig(response, format='png')
        return response
    

    You still need to have the canvas instantiated, though.

提交回复
热议问题