在django网站中嵌入matplotlib图

问题描述:

当用户点击上传按钮上传他们的csv时,我的网站应该返回一个matplotlib图。我将情节保存到缓冲区,现在只需要在上传按钮所在的页面显示。在django网站中嵌入matplotlib图

我是一个初学者的Django所以下面是我做的(警告:一些伪提前)

views.py是的,我可以看到,通过plotResult(request, csvfile_path)返回的httprequest不与互动list.html。我不知道如何得到它

def list(request): 
    #Working code for uploading a csv and retrieving the path to the uploaded file 
    if document uploaded: 
     return plotResult(request, csvfile_path) 

    return render(
     request, 
     'list.html', 
     {'documents': documents, 'form': form} 
    ) 

def plotResult(request, sorted_dir): 
    # Bunch of code for computing the plot - functions in custom_script.py 
    return Plot_Composite_metrics(bunch of parameters) 

Plot_Composite_metrics在custom_script.py这是在同一目录views.py并包含许多功能计算的情节:

def Plot_Composite_metrics(bunch of parameters): 
    # More code for computing the plot 
    ax = plt.subplot2grid((3,4), (0,0), colspan=4) 
    # Code for adding attributes to ax. 

    # Store the now built image in a string buffer 
    buffer = StringIO.StringIO() 
    canvas = pylab.get_current_fig_manager().canvas 
    canvas.draw() 
    pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) 
    pilImage.save(buffer, "PNG") 
    pylab.cose() 

    return HttpResponse(buffer.getvalue(), mimetype="image/png") 

list.html我有什么,我需要生成上传功能,下面来产生matplotlib阴谋:

<img src="data:image/png;base64,{{graphic|safe}}"> 

当我运行这个时没有崩溃,上面的img标签起初只有它的空填充。然后在上传网站后返回图表,但是在它自己的页面上,而不是在上传按钮下面的img标签处。我该如何做到这一点,使matplotlib图出现嵌入在同一页面上?

万一知道剧情的样子是很重要的,在这里:here

我在SVG格式类似用途救了我的情节,

import six 

fig = plt.figure() 
# plot some data 
tmp = six.StringIO() 
fig.savefig(tmp, format='svg', bbox_inches='tight') 

template = loader.get_template('path_to_/template.html') 
c = Context({ 'svg': tmp.getvalue() }) 
return HttpResponse(template.render(c)) 

在模板文件中,

{% if svg %} 
<div style="width:60em;height:46em"> 
    {% autoescape off %} 
    {{ svg }} 
    {% endautoescape %} 
</div>