python Matplotlib冻结与线程

时间:2020-10-14 18:47:23

标签: python multithreading matplotlib

问题:使程序成为多线程后,matplotlib无法正确更新图形 我正在使用ION模式,每次数据帧更新后都暂停了

有效的单线程代码:

...

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')

...

多线程代码,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'], 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

...

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

0 个答案:

没有答案
相关问题