UserWarning:在主线程之外启动 Matplotlib GUI 可能会失败

new*_*new 12 python matplotlib

我正在尝试返回数据列表和绘图。它们确实显示在 HTML 代码中而不是网页中。当我查看终端时它显示"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')
Run Code Online (Sandbox Code Playgroud)

omo*_*osh 23

试试这个,它对我有用

import matplotlib
matplotlib.use('agg')
Run Code Online (Sandbox Code Playgroud)

Agg 是一个非交互式后端,只能写入文件。有关更多信息和其他解决方法,请参阅https://matplotlib.org/stable/users/explain/backends.html


小智 0

这只是警告,它会运行,但可能是一个非常痛苦的问题。我不完全是专家,但我也有同样的警告,如果您尝试在主线程之外的线程中使用 matplotlib,情况可能会更糟。由于某些原因,matplotlib 在线程上不能很好地工作,这可能会导致您的应用程序崩溃。