首页 > 解决方案 > 当我同时发送两个请求时,matplotlib 中的绘图重叠

问题描述

我对 Flask 和 matplotlib 有疑问。我编写了一个从 matplotlib 返回图表的简单 API。当两个用户同时发送请求时,即使我为图表创建了单独的类,图表也会重叠。

这是我的代码:

class WykresXT:
    def make(self, amp, okres):
        name = random.randint(0, 1000000)
        time = np.arange(0, 20, 0.1)
        plot.plot(time, calc_xt(amp=float(amp), czas=time, okres_d=float(okres)))
        plot.title('Wykres x(t)')
        plot.xlabel('t (czas)')
        plot.ylabel('x (wychylenie)')
        plot.grid(True, which='both')
        plot.axhline(y=0, color='k')
        plot.savefig(str(name) + '.png')
        plot.close()
        plot.figure().clear()
        return str(name) + '.png'


@app.route('/wykres_x', methods=['GET'])
def wykres_x():
    args = {"amp": request.args.get('amp'), "okres": request.args.get('okres'), "faza": request.args.get('faza')}
    if args["amp"] is not None and args["okres"] is not None and args["faza"] is not None:
        wykres = WykresXT()
        return send_file(wykres.make(args["amp"], args["faza"], args["okres"]))
    else:
        return "podaj: '?amp=' '&okres=' '&faza='"

还有一个重叠问题的例子:

重叠图表示例

标签: pythonmatplotlibflaskchartsrest

解决方案


好的,所以我能够重现您的错误并设法修复它。在那里测试,看看它是否适合你。

我创建了这个脚本来一次发送多个请求,取自另一个 SO 帖子。

import requests
from concurrent.futures import ThreadPoolExecutor

def get_url(url):
        return requests.get(url)

list_of_urls = [
        'http://0.0.0.0:25565/wykres_x?amp=5&okres=10',
        'http://0.0.0.0:25565/wykres_x?amp=10&okres=10',
        'http://0.0.0.0:25565/wykres_x?amp=15&okres=10',
        'http://0.0.0.0:25565/wykres_x?amp=20&okres=10',
        'http://0.0.0.0:25565/wykres_x?amp=5&okres=15',
        'http://0.0.0.0:25565/wykres_x?amp=10&okres=20',
        'http://0.0.0.0:25565/wykres_x?amp=5&okres=30',
        'http://0.0.0.0:25565/wykres_x?amp=10&okres=40'
        ]

with ThreadPoolExecutor(max_workers=10) as pool:
        print(list(pool.map(get_url,list_of_urls)))

当我在您的服务器运行时运行此程序时,正如预期的那样,我得到了一些彩色图表。

然后,正如我在评论中提到的,我将 pyplot 调用从隐式更改为显式。这是你的课。

class WykresXT:
    def make(self, amp, okres):
        name = random.randint(0, 1000000)
        time = np.arange(0, 20, 0.1)
        fig, ax = plot.subplots()  # <-- here is the start of the different part
        ax.plot(time, calc_xt(amp=float(amp), czas=time, okres_d=float(okres)))
        ax.set_title('Wykres x(t)')
        ax.set_xlabel('t (czas)')
        ax.set_ylabel('x (wychylenie)')
        ax.grid(True, which='both')
        ax.axhline(y=0, color='k')
        fig.savefig(str(name) + '.png') # <-- end of the modified part
        plot.close()
        plot.figure().clear()
        return str(name) + '.png'

它现在创建了一堆图形,按照您的需要全部分开。


推荐阅读