Python: How to show matplotlib in flask [duplicate] Python: How to show matplotlib in flask [duplicate] flask flask

Python: How to show matplotlib in flask [duplicate]


You can generate the image on-the-fly in Flask URL route handler:

import ioimport randomfrom flask import Responsefrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvasfrom matplotlib.figure import Figure@app.route('/plot.png')def plot_png():    fig = create_figure()    output = io.BytesIO()    FigureCanvas(fig).print_png(output)    return Response(output.getvalue(), mimetype='image/png')def create_figure():    fig = Figure()    axis = fig.add_subplot(1, 1, 1)    xs = range(100)    ys = [random.randint(1, 50) for x in xs]    axis.plot(xs, ys)    return fig

Then you need to include the image in your HTML template:

<img src="/plot.png" alt="my plot">


As @d parolin pointed out, the figure generated by matplotlib will need to be saved before being rendered by the HTML. In order to serve images in flask by HTML, you will need to store the image in your flask file directory:

static/  images/    plot.png --> store plots heretemplates/

Therefore, in your application, use plt.savefig:

@app.route('/test')def chartTest():  lnprice=np.log(price)  plt.plot(lnprice)     plt.savefig('/static/images/new_plot.png')  return render_template('untitled1.html', name = 'new_plot', url ='/static/images/new_plot.png')

Then in untitled1.html:

  <p>{{ name }}</p>  <img src={{ url}} alt="Chart" height="42" width="42">