Others


RuntimeError: main thread is not in main loop with Matplotlib and Flask


If we want to save the matplotlib image using Flask, we will obtain 'RuntimeError: main thread is not in main loop with Matplotlib and Flask' Error.

Use the following code to solve the Error.

 
from flask import Flask,render_template
app=Flask(__name__)

@app.route("/generate_plot",methods=['GET','POST'])
def generate_plot():

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    plt.figure()
    x = ["Name1","Name2"]
    h = [80,89]
    c = ['green','red']
    plt.xlabel('Mark', fontsize=12)
    plt.title('Student Marks')
    plt.ylabel('Name', fontsize=12)
    plt.bar(x, height = h, color = c)
    plt.savefig('static/img/plot1.png')
    
    return "Plot Saved"
    
if __name__=='__main__':
    app.run(debug=True)