Skip to content
Snippets Groups Projects

Adding matplotlib Figure directly into `<img>`'s tag `src`

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by mstankie

    This shows how to embed plot genertaed by matplotlib directly into HTML code in flask view.

    Edited
    generate_figure.py 908 B
    from flask import render_template
    import io
    import base64
    
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    @app.route("/mysuperplot", methods=["GET"])
    def plotView():
    
        # Generate plot
        fig = Figure()
        axis = fig.add_subplot(1, 1, 1)
        axis.set_title("title")
        axis.set_xlabel("x-axis")
        axis.set_ylabel("y-axis")
        axis.grid()
        axis.plot(range(5), range(5), "ro-")
        
        # Convert plot to PNG image
        pngImage = io.BytesIO()
        FigureCanvas(fig).print_png(pngImage)
        
        # Encode PNG image to base64 string
        pngImageB64String = "data:image/png;base64,"
        pngImageB64String += base64.b64encode(pngImage.getvalue()).decode('utf8')
        
        return render_template("image.html", image=pngImageB64String)
    
    # In the image.html jinja2 template use the following <img> to add the plot:
    # <img src="{{ image }}"/>
    • t h @proftrex ·

      That gives:

      TypeError: bad operand type for unary +: 'str'

      I think the line 28 should be

          return render_template("image.html", image=pngImageB64String)

      i.e. without the +

    • Thanks! I am relative new to Python and Web Programming and was trying to figure out a way for embeding Matplotlib int HTML. This solution sounds fine and easy to implement.

    • I made an account just to comment on this. From a senior software engineering student working on a flask web app for senior design, I thank you from the bottom of my heart!

    • how to set in confussion matrix?

    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment