[Fixed]-Python – How to output matplotlib plots as images to the browser in Django

1👍

This seems to be an old question and without activity for a while but I bumped into this facing a similar problem recently. I was able to solve it so I thought I could share my solution. Here it goes.
In your html template you should have a button to trigger an ajax request. For example:

***index.html***

<a href="#" id="plot">Plot</a>

<div id="imagediv"></div>

$('#plot').click(function(){
$.ajax({
        "type"     : "GET",
        "url"      : "/Plot/",
        "data"     : "str",
        "cache"    : false,
        "success"  : function(data) {
            $('#imagediv').html(data);
        }
});

});

Your views.py (or a separate file if you wish for example: utils.py) should have a function to draw the graph.

***utils.py***

@login_required()
def MatPlot(request):
    # Example plot
    N = 50
    x = np.random.rand(N)
    y = np.random.rand(N)
    colors = np.random.rand(N)
    area = np.pi * (15 * np.random.rand(N)) ** 2
    plt.scatter(x, y, s=area, c=colors, alpha=0.5)
    # The trick is here.
    f = io.BytesIO()
    plt.savefig(f, format="png", facecolor=(0.95, 0.95, 0.95))
    encoded_img = base64.b64encode(f.getvalue()).decode('utf-8').replace('\n', '')
    f.close()
    # And here with the JsonResponse you catch in the ajax function in your html triggered by the click of a button
return JsonResponse('<img src="data:image/png;base64,%s" />' % encoded_img, safe=False)

Of course you need to wire this function with a url, so:

***urls.py***
url(r'^plot/$', Matplot, name='matplot')

Leave a comment