Reputation: 2187
After compute the scatter plot with
plt.scatter(...)
I can preview the graph with
plt.show()
However, I wish to save the plot with some sort of function like savefig() which store the image in a variable instead of a file, then return the variable in http response as content/png in django web framework
Upvotes: 2
Views: 6139
Reputation: 3698
You can return the plot as a png image like this:
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
from django.http import HttpResponse
def graph(request):
fig = Figure()
# draw your plot here ......
ax = fig.add_subplot(111)
# .............
canvas = FigureCanvasAgg(fig)
response = HttpResponse(content_type = 'image/png')
canvas.print_png(response)
return response
But, since matplotlib 2.2.0 print_png function doesn't take HttpResponse anymore.
Upvotes: 1
Reputation: 2187
After further searching, I found Returning MatPotLib image as string
This solution solved my problem. Thank you everyone for the help.
Upvotes: 1
Reputation: 11942
I suggest you use mpld3
that is designed for that, here's a guide
Specifically, have a look at mpld3.fig_to_html()
Upvotes: 0
Reputation: 11560
use
plt.savefig(save_file)
read more at: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
Upvotes: 0