2017-07-18 144 views
2

計算與在HTTP響應返回圖片

plt.scatter(...) 

散點圖我可以

plt.show() 

但是預覽圖之後,我希望保存的情節與一些有點像savefig功能( )將圖像存儲在一個變量而不是文件中,然後在http響應中將變量作爲content/png返回到django web框架中

+0

'plt.show()'的輸出格式是什麼? – MiniGunnR

+0

@MiniGunnR它實際上在新窗口中顯示情節。 –

+0

@MiniGunnR'plt.show()'將使用'qt'呈現我想。 – Rahul

回答

1

可以返回情節作爲這樣的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了。

0

我建議你使用mpld3這是專爲,here's a guide

具體來說,看看mpld3.fig_to_html()