Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. ***index.html***
  2.  
  3. <a href="#" id="plot">Plot</a>
  4.  
  5. <div id="imagediv"></div>
  6.  
  7. $('#plot').click(function(){
  8. $.ajax({
  9. "type" : "GET",
  10. "url" : "/Plot/",
  11. "data" : "str",
  12. "cache" : false,
  13. "success" : function(data) {
  14. $('#imagediv').html(data);
  15. }
  16. });
  17.  
  18. ***utils.py***
  19.  
  20. @login_required()
  21. def MatPlot(request):
  22. # Example plot
  23. N = 50
  24. x = np.random.rand(N)
  25. y = np.random.rand(N)
  26. colors = np.random.rand(N)
  27. area = np.pi * (15 * np.random.rand(N)) ** 2
  28. plt.scatter(x, y, s=area, c=colors, alpha=0.5)
  29. # The trick is here.
  30. f = io.BytesIO()
  31. plt.savefig(f, format="png", facecolor=(0.95, 0.95, 0.95))
  32. encoded_img = base64.b64encode(f.getvalue()).decode('utf-8').replace('n', '')
  33. f.close()
  34. # And here with the JsonResponse you catch in the ajax function in your html triggered by the click of a button
  35. return JsonResponse('<img src="data:image/png;base64,%s" />' % encoded_img, safe=False)
  36.  
  37. ***urls.py***
  38. url(r'^plot/$', Matplot, name='matplot')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement