Python 在HTTP响应中返回图像
在计算散点图后,使用Python 在HTTP响应中返回图像,python,django,matplotlib,Python,Django,Matplotlib,在计算散点图后,使用 plt.scatter(...) 我可以用鼠标预览图表 plt.show() 但是,我希望使用诸如savefig()之类的函数来保存绘图,该函数将图像存储在变量中而不是文件中,然后在http响应中将变量返回为django web framework中的content/png plt.savefig(save_file) 阅读更多信息:您可以将绘图作为png图像返回,如下所示: from matplotlib.backends.backend_agg import Fi
plt.scatter(...)
我可以用鼠标预览图表
plt.show()
但是,我希望使用诸如savefig()之类的函数来保存绘图,该函数将图像存储在变量中而不是文件中,然后在http响应中将变量返回为django web framework中的content/png
plt.savefig(save_file)
阅读更多信息:您可以将绘图作为png图像返回,如下所示:
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
但是,由于matplotlib 2.2.0 print_png函数不再需要HttpResponse。我建议您使用专门为此设计的
mpld3
具体地说,看看mpld3.fig_to_html()在进一步搜索之后,我发现
这个解决方案解决了我的问题。谢谢大家的帮助。plt.show()的输出格式是什么?@minigunr它实际上在一个新窗口中显示了绘图。@minigunr
plt.show()
将使用qt
进行渲染。