python pyplot mathplotlib在一分钟后变慢

2024-04-30 03:46:39 发布

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

我用串口监听一些数据。我在tkinter输出和pygame中完成的仪表板中显示这些值。一切都很好

现在我尝试将绘图仪窗口与pyplot集成。用户可以选择6个值中的2个值。1-2分钟后,绘图仪的速度减慢,我认为绘图仪在某个地方保留了图形的旧值。我怎样才能更好地处理这个问题

import matplotlib.pyplot as plt

初始

def initPlotter():
    global showPlotterFlag
    global lastPlotterChoice
    global fevent
    global fig
    global ax1, ax2
    global start

    start = time.time()

    plt.style.use('bmh')
    fig, (ax1, ax2) = plt.subplots(2)
    fig.suptitle('mobile instruments plot')
    plottertext = ["aaaaaaaaa", "bbbbbbbbbbbbbb",
                           "cccccccccc", "ddddddddd", "eeeeeee", "ffffffffff"]
    plotterAxis = [[0, 5], [50, 150], [0, 6000], [0.7, 1.3], [50, 250], [8, 16]]

    maxVal = 0

    for i in range(6):
        if lastPlotterChoice[i] == 1:
            maxVal += 1
            if (maxVal == 1):
                #ax1.set_title(plottertext [i])
                ax1.set_ylabel(plottertext [i])
                ax1.set_ylim([plotterAxis[i][0], plotterAxis[i][1]])
            if (maxVal == 2):
                #ax2.set_title(plottertext [i])
                ax2.set_ylabel(plottertext [i])
                ax2.set_ylim(plotterAxis[i][0], plotterAxis[i][1])
    if maxVal == 1:
        ax2.set_ylabel('nicht benutzt')
    fevent = plt.connect('close_event', handle_close)

    plt.show(block=False)
    showPlotterFlag=True

在主回路上:

def showPlotterDisplay():
    global yps
    global valueInArray
    global valuesCurr
    global ax1, ax2
    global start

    yps += 1
    maxVal = 0

    now = time.time() - start

    for i in range(6):
        if lastPlotterChoice[i] == 1:
            maxVal += 1
            if (maxVal == 1):
                ax1.set_xlim([now-12, now+3])
                ax1.plot(now, valueInArray[i], 'g.')  # valueInArray[1] r+

            if (maxVal == 2):
                ax2.set_xlim([now-12, now+3])
                ax2.plot(now, valueInArray[i], 'r.')  # valueInArray[1] r+

Tags: iftimepltglobalstartnow绘图仪set
1条回答
网友
1楼 · 发布于 2024-04-30 03:46:39

matplotlib中,每次plot(或以任何方式在轴上绘制,例如使用imshow)时,您都没有清除以前的状态,您只是在添加之前的状态

在长循环中,这会导致轴上的参与者超载,从而降低代码的速度

假设不需要在一个轴上同时绘制所有直线,一种可能的解决方案是在下一次迭代绘制数据之前ax.clear()绘制轴。 另一方面,如果在一个轴上需要大量数据,最好的办法是在非交互模式下(plt.ioff()),plot所有需要的数据,最后show()/保存图形(这样可以跳过所有中间渲染和重绘)。最终的情节仍将缓慢,但中间的步骤不会那么糟糕

相关问题 更多 >