Matplotlib into a Django Template

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

        from io import BytesIO
        import base64
        import matplotlib.pyplot as plt
        import numpy as np
    
        def graphic(request):
    
            pos = np.arange(10)+ 2 
    
            fig = plt.figure(figsize=(8, 3))
            ax = fig.add_subplot(111)
    
            ax.barh(pos, np.arange(1, 11), align='center')
            ax.set_yticks(pos)
            ax.set_yticklabels(('#hcsm',
                '#ukmedlibs',
                '#ImmunoChat',
                '#HCLDR',
                '#ICTD2015',
                '#hpmglobal',
                '#BRCA',
                '#BCSM',
                '#BTSM',
                '#OTalk',), 
                fontsize=15)
            ax.set_xticks([])
            ax.invert_yaxis()
    
            ax.set_xlabel('Popularity')
            ax.set_ylabel('Hashtags')
            ax.set_title('Hashtags')
    
            plt.tight_layout()
    
            buffer = BytesIO()
            plt.savefig(buffer, format='png')
            buffer.seek(0)
            image_png = buffer.getvalue()
            buffer.close()
    
            graphic = base64.b64encode(image_png)
            graphic = graphic.decode('utf-8')
    
            return render(request, 'graphic.html',{'graphic':graphic})
    

    and in the template:

    
    

    I have:

    matplotlib==3.0.2 and Django==2.1.4

提交回复
热议问题