Matplotlib成为Django模板

Ces*_*ora 9 python django matplotlib

我使用python 3.4和Django 1.8.我想在Django模板中"打印"matplotlib结果.我几天前就达成了这个,所以我继续使用我的Django App的其他东西.现在,我不知道为什么,我要向朋友展示结果,而我的模板带有matplotlib图,现在显示了一个很大的代码!我不知道为什么会发生这种情况,因为我的观点在显示正确的图形时没有任何变化!请帮我!

这是我的看法!

from django.shortcuts import render
from matplotlib import pylab
from pylab import *
import PIL
import PIL.Image
import io
from io import *

def graphic(request):

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('Popularity')
ylabel('Hashtags')
title('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")
content_type="Image/png"
buffercontent=buffer.getvalue()


graphic = (buffercontent ,content_type)
pylab.close()


return render(request, 'graphic.html',{'graphic':graphic})
Run Code Online (Sandbox Code Playgroud)

当然,在我的graphic.html中,一个名为{{graphic}}的变量在blockcontent中!

这在我的模板中显示了正确的结果!发生什么事?现在,有时当我运行我的模板时,它会显示一个很大的代码,或者只是告诉我这个django错误:

异常值:
主线程不在主循环中

异常位置:blit中的C:\ Python34\lib\site-packages\matplotlib\backends\tkagg.py,第17行

救命!

小智 10

    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})
Run Code Online (Sandbox Code Playgroud)

并在模板中:

<img src="data:image/png;base64,{{ graphic|safe }}">
Run Code Online (Sandbox Code Playgroud)

我有:

matplotlib==3.0.2 和 Django==2.1.4


Mar*_*esh 6

编辑:

尝试

graphic = cStringIO.StringIO()
canvas.print_png(graphic)
return render(request, 'graphic.html',{'graphic':graphic})
Run Code Online (Sandbox Code Playgroud)

您必须指定您的图像是二进制字符串:

<img src="data:image/png;base64,{{graphic|safe}}">
Run Code Online (Sandbox Code Playgroud)

或者实际将其保存到文件系统并提供路径。

或者,您可以使用Bokeh,它可以为您提供 html + javascript 将绘图直接嵌入模板中,然后动态生成并带来不错的功能。