python - python 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
...
请帮助我理解为什么这不起作用,谢谢!
解决方案
推荐阅读
- python - 蟒蛇说“'pyspark'没有属性'ml'”,我不知道如何解决这个问题
- mysql - 如何使用codeigniter选择多个where条件?
- php - Laravel excel library prints blank excel file
- php - 我无法登录服务器 - Laravel 6
- java - 已解决!:我的代码中的 for 循环不会重复重复、收集输入并将其放入数组中
- r - 使用 R 过滤到特定日期范围
- django - djanago 频道 CRITICAL 侦听失败:无法在 0.0.0.0:x 上侦听:[Errno 98] 地址已在使用中
- css - Bootstrap 4 移动菜单
- python - 将字典转换为 CSV 格式
- r - Transmute_at 每一列都基于 r 中的另一列