渲染matplotlib并在烧瓶中进行Seaborn

时间:2020-06-27 14:12:32

标签: python matplotlib flask seaborn

我正在尝试在烧瓶模板中渲染matplotlib和seaborn图的图像,如下所示:

from flask import Flask, render_template, make_response
import matplotlib.pyplot as plt
import seaborn as sns
from io import BytesIO

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@app.route('/plot.png')
def plot():
       fig = Figure() 
       plot= fig.add_subplot(1, 1, 1)
       jb=np.array([1.74, 0.82, 0.32, 1.33, 1.03, 0.31, 1.09, 1.0, 0.98, 1.76, 0.73, 0.37, 0.62, 
                             0.24, 0.15, 1.05, 0.99, 1.14, 0.9, 0.29, 0.95,1.41, 0.81])
       you=1.4
       tipmedian=1.3
       ax = jobTip.plot(kind='density', color='black')
       ax.set_xlabel('Years in Jobcode')



       # vertical dotted line originating at median value
       plt.axvline(tipmedian, linestyle='dashed', linewidth=2, color='black')
       plt.text(tipmedian, 1.3,'Group Median='+str(tipmedian)+' years(s)',rotation='vertical')

       # vertical dotted line originating at current user value
       plt.axvline(you, linestyle='dashed', linewidth=2, color='orange')
       plt.text(you, 1.3,'You='+str(you)+' years(s)',rotation='vertical')

       g=sns.kdeplot(jobTip, color="grey", shade=True)    
       g.legend_.remove() 
       canvas = FigureCanvas(fig)
       output = BytesIO()    
       canvas.print_png(output)
       response = make_response(output.getvalue())
       response.mimetype = 'image/png'
       return response

我正在尝试将图作为图像发送到如下模板(在烧瓶jinja html中):

       <img src="/plot.png" >

这里,我不想保存图像以在模板中绘制图,因为它将根据用户的请求数据动态生成。我正在努力破解。我很感激能帮助我。

1 个答案:

答案 0 :(得分:0)

就我而言,图像完美呈现而没有任何问题:

 def Index():
    jb=np.array([1.74, 0.82, 0.32, 1.33, 1.03, 0.31, 1.09, 1.0, 0.98, 1.76, 0.73, 0.37, 0.62, 
                         0.24, 0.15, 1.05, 0.99, 1.14, 0.9, 0.29, 0.95,1.41, 0.81])
   
    ............
    ............

    img = BytesIO()
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)
    plot_url = base64.b64encode(img.getvalue()).decode('utf8')
    return render_template(plot_url=plot_url)

在index.html中:

    <div>
                  
                    <img src="data:image/png;base64, {{ plot_url }}">
    </div>