当我同时发送两个请求时,matplotlib中的绘图重叠

2024-09-29 21:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是我的密码:

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='"

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

example of overlapping charts


Tags: namenonegetreturntimeplotisrequest
1条回答
网友
1楼 · 发布于 2024-09-29 21:27:17

好的,所以我能够复制你的错误,并设法在我这端修复它。在那边测试一下,看看它是否适合你

我创建这个脚本是为了一次发送多个请求,这些请求来自另一个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'

它现在创建了一组数字,所有这些数字都按照您的需要分开

相关问题 更多 >

    热门问题