Skip to main content
 首页 » 编程设计

python之在 django 站点中嵌入 matplotlib 图

2025年05月04日25grandyang

当用户点击上传按钮上传他们的 csv 时,我的网站应该返回一个 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 图嵌入同一页面?

如果有机会了解剧情很重要,请点击这里:

请您参考如下方法:

出于类似目的,我已将我的绘图保存为 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>