0

I'm using Python- Pandas, Numpy to implement some financial indicators and strategies. I'm also using the Matlab library in Python to plot my data.

On the other hand, I'm using Django for the web-end part of my project.

What I want to do is to output my matlab plot as an image to the browser using Django.

Any recommendation is appreciated. Thank you so much!

4

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

This worked well for me! I just have a question for you. Is using the Base64 encoding going to put a larger strain on the client and/or server?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.