Matplotlib into a Django Template

后端 未结 5 2098
时光取名叫无心
时光取名叫无心 2021-01-02 03:17

Im using python 3.4 and Django 1.8. I want to \"print\" a matplotlib result in a Django template. I reach this a few days ago, so I continue in other things of my Django App

5条回答
  •  悲哀的现实
    2021-01-02 03:27

    def show(request):
    
    x = np.arange(10)
    y = x
    fig = plt.figure()
    plt.plot(x, y)
    canvas = fig.canvas
    buf, size = canvas.print_to_buffer()
    image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
    buffer=io.BytesIO()
    image.save(buffer,'PNG')
    graphic = buffer.getvalue()
    graphic = base64.b64encode(graphic)
    buffer.close()
    return render(request, 'graphic.html',{'graphic':graphic})
    

提交回复
热议问题