Passing a matplotlib figure to HTML (flask)

前端 未结 5 1659
遥遥无期
遥遥无期 2020-11-29 20:41

I am using matplotlib to render some figure in a web app. I\'ve used fig.savefig() before when I\'m just running scripts. However, I need a function to return a

5条回答
  •  悲&欢浪女
    2020-11-29 21:13

    Python 3

    I went through a lot of trouble with errors like - Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!

    For all those who want to use matplotlib with flask and render the graph on an html page in python 3, here you go -

    In the __init__.py

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from flask import Flask, render_template
    from io import BytesIO
    import base64
    
        @app.route('/plot')
        def plot():
            img = BytesIO()
            y = [1,2,3,4,5]
            x = [0,2,1,3,4]
    
            plt.plot(x,y)
    
            plt.savefig(img, format='png')
            plt.close()
            img.seek(0)
            plot_url = base64.b64encode(img.getvalue()).decode('utf8')
    
            return render_template('plot.html', plot_url=plot_url)
    

    In flaskr/templates/plot.html

    
    heatmap - 
    

    Heatmap

提交回复
热议问题