python Matplotlib因线程而冻结

python Matplotlib因线程而冻结,python,multithreading,matplotlib,Python,Multithreading,Matplotlib,问题:进行程序多线程处理后,matplotlib无法正确更新图形 我使用的是离子模式,每次数据帧更新后都会暂停 工作正常的单线程代码: 多线程代码,matplotlib不再更新图形 请帮助我理解为什么这不起作用,谢谢 Matplotlib不是线程安全的。如果你真的想让不同的线程写入同一个图形,听起来你需要做一些工作。是的,如果我想让另一个线程来绘制,我可以理解,但是在这种情况下,绘图仍然在主线程中(正确吗?),只有数据在其他线程中生成,或者我缺少什么? plt.ion() fig, ax

问题:进行程序多线程处理后,matplotlib无法正确更新图形 我使用的是离子模式,每次数据帧更新后都会暂停

工作正常的单线程代码:

多线程代码,matplotlib不再更新图形


请帮助我理解为什么这不起作用,谢谢

Matplotlib不是线程安全的。如果你真的想让不同的线程写入同一个图形,听起来你需要做一些工作。是的,如果我想让另一个线程来绘制,我可以理解,但是在这种情况下,绘图仍然在主线程中(正确吗?),只有数据在其他线程中生成,或者我缺少什么?
plt.ion()
fig, axs = plt.subplots(2, 3)
fig.suptitle('Candle Charts')
fig.set_tight_layout(True)
plt.style.use('bmh')
fig.canvas.draw()

def f_plot_candle_chart(dataframe, row, column, charttitle):
    axs[row, column].cla()
    axs[row, column].set_title(charttitle)
    axs[row, column].tick_params(axis='x', rotation=90)
    axs[row, column].plot(dataframe['a'].tail(50), label='a', color='green', alpha=1, linewidth=1.0)
    axs[row, column].plot(dataframe['b'].tail(50), label='b', color='blue', alpha=1, linewidth=1.0)
    plt.pause(0.1)
    plt.show(block=False)

def f_random_a(a):
    a = a + 5
    return a

def f_random_b(b):
    b = b + 6
    return b

while True:
    a = f_random_a(a)
    b = f_random_b(b)
    new_row = {'a': a, 'b': b}
    dataframe = dataframe.append(new_row, ignore_index=True)
    f_plot_candle_chart(dataframe, 1, 1, '1m')
plt.ion()
fig, axs = plt.subplots(2, 3)
fig.suptitle('Candle Charts')
fig.set_tight_layout(True)
plt.style.use('bmh')
fig.canvas.draw()

def f_plot_candle_chart(dataframe, row, column, charttitle):
    axs[row, column].cla()
    axs[row, column].set_title(charttitle)
    axs[row, column].tick_params(axis='x', rotation=90)
    axs[row, column].plot(dataframe['a'], label='a', color='green', alpha=1, linewidth=1.0)
    axs[row, column].plot(dataframe['b'], label='b', color='blue', alpha=1, linewidth=1.0)
    plt.pause(1)
    plt.show(block=False)

def f_random_a():
    while True:
        global update_a
        global a
        if not update_a:
            a = a + 5
            update_a = True


def f_random_b():
    while True:
        global update_b
        global b
        if not update_b:
            b = b + 6
            update_b = True


x1 = threading.Thread(target=f_random_a, daemon=True)
x1.start()
x2 = threading.Thread(target=f_random_b, daemon=True)
x2.start()

while True:

    if update_b and update_a:
        new_row = {'a': a, 'b': b,}
        dataframe = dataframe.append(new_row, ignore_index=True)
        f_plot_candle_chart(dataframe, 1, 1, '1m')
        update_a = False
        update_b = False