【问题标题】:Return image in HTTP response在 HTTP 响应中返回图像
【发布时间】:2017-07-18 08:57:29
【问题描述】:

计算散点图后

plt.scatter(...)

我可以预览图表

plt.show()

但是,我希望使用某种函数(例如 savefig() 将图像存储在变量而不是文件中)来保存绘图,然后在 http 响应中将变量作为 django web 框架中的 content/png 返回

【问题讨论】:

  • plt.show() 的输出格式是什么?
  • @MiniGunnR 它实际上在一个新窗口中显示了情节。
  • @MiniGunnR plt.show() 我猜将使用qt 渲染。

标签: python django matplotlib


【解决方案1】:

经过进一步搜索,找到Returning MatPotLib image as string

这个解决方案解决了我的问题。谢谢大家的帮助。

【讨论】:

    【解决方案2】:

    您可以像这样将绘图返回为 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。

    【讨论】:

      【解决方案3】:

      使用

      plt.savefig(save_file)
      

      阅读更多:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

      【讨论】:

        【解决方案4】:

        我建议你使用专为此设计的mpld3here's a guide

        具体看mpld3.fig_to_html()

        【讨论】:

          猜你喜欢
          • 2011-03-05
          • 2020-01-21
          • 2014-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-29
          • 2019-06-25
          相关资源
          最近更新 更多