How to show Matplotlib in Flask?

MatplotlibPythonData Visualization

To show a plot in Flask, we can take the following steps−

  • Make a small application.
  • To run Flask application, go to the current directory.
  • $ export
  • $ flask run
  • Open the browser, hit url:
  • To plot the figure, we can create data points for x and y using random.
  • Plot data points, x and y, on the created axis.
  • Write a figure into png figure format.
  • Retrieve the entire contents of the BytesIO object.


import io
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from flask import Flask
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
app = Flask(__name__)
def plot_png():
   fig = Figure()
   axis = fig.add_subplot(1, 1, 1)
   xs = np.random.rand(100)
   ys = np.random.rand(100)
   axis.plot(xs, ys)
   output = io.BytesIO()
   return Response(output.getvalue(), mimetype='image/png')


Published on 15-May-2021 12:43:32