Matplotlib into a Django Template

后端 未结 5 2082
时光取名叫无心
时光取名叫无心 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:40

    The final solution was to create a special view that returns the matplotlib plot in an empty template, like this:

    def grafico (rquest):
        pos = arange(10)+ 2 
    
        barh(pos,(1,2,3,4,5,6,7,8,9,10),align = 'center')
    
        yticks(pos,('#hcsm','#ukmedlibs','#ImmunoChat','#HCLDR','#ICTD2015','#hpmglobal','#BRCA','#BCSM','#BTSM','#OTalk'))
    
        xlabel('Popularidad')
        ylabel('Hashtags')
        title('Gráfico de Hashtags')
        subplots_adjust(left=0.21)
    
        buffer = io.BytesIO()
        canvas = pylab.get_current_fig_manager().canvas
        canvas.draw()
        graphIMG = PIL.Image.fromstring('RGB', canvas.get_width_height(), canvas.tostring_rgb())
        graphIMG.save(buffer, "PNG")
        pylab.close()
    
        return HttpResponse (buffer.getvalue(), content_type="Image/png")
    

    The next step is to put in your template this:

    
    

    And thats all!

提交回复
热议问题