1

I am trying render Image of matplotlib and seaborn plot in flask template like below:

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

I am trying send plot as image to template like below(in flask jinja html):

       <img src="/plot.png" >

Here I don't want to save image to render plot in template, since it will generate dynamically according to request data from user. I am struggling to crack this. I appreciate if any can help me.

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40
Sanjay Chintha
  • 326
  • 1
  • 4
  • 21

1 Answers1

0

In my case, Image rendered perfectly without any issue:

 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)

in index.html:

    <div>
                  
                    <img src="data:image/png;base64, {{ plot_url }}">
    </div>
Sanjay Chintha
  • 326
  • 1
  • 4
  • 21