Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail

I am trying to return the data list and plot. They do display in the HTML code instead of web page. When I look at the terminal it shows "UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail."

from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd


def extract(request):

    if request.method == 'POST':
        if request.FILES.get('document'):
            file = request.FILES['document']

            if 'data' in request.POST:
                data = df = pd.read_excel(file)
                mpl.rcParams['agg.path.chunksize'] = 10000
                plt.plot(data["time"], data["make"], label='male')
                plt.plot(data["time"], data["female"], label='female')

                plt.xlabel('T')
                plt.ylabel('M and F')
                plt.legend()

                buffer = BytesIO()
                plt.savefig(buffer, format='png')
                buffer.seek(0)
                image_png = buffer.getvalue()
                buffer.close()

                graphic = base64.b64encode(image_png)
                graphic = graphic.decode('utf-8')


                dic_result = {'graphic': graphic}

                dataa = []
                for index in range(len(data["make"])):
                   data.append(tuple(dataa["male"][index], dataa["female"][index]))

                return render(request, 'bothdata.html', {'data': dataa}, dic_result)


    return render(request, 'extract.html')
like image 378
new Avatar asked Sep 12 '25 16:09

new


1 Answers

try this, it worked for me

import matplotlib
matplotlib.use('agg')

Agg, is a non-interactive backend that can only write to files. For more information and other ways of solving it see https://matplotlib.org/stable/users/explain/backends.html

like image 137
omosh Avatar answered Sep 15 '25 05:09

omosh