Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ***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);
- }
- });
- ***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)
- ***urls.py***
- url(r'^plot/$', Matplot, name='matplot')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement