简体   繁体   English

Matplotlib:图标题没有更新?

[英]Matplotlib: Figure title does not update?

I need to make a plot and update it many times (100's or 1000's) so I need Python to update it very quickly.我需要制作一个 plot 并多次更新(100 或 1000 次),所以我需要 Python 快速更新它。 I found a wonderful solution but I am not allowed to add a comment.我找到了一个很好的解决方案,但我不允许添加评论。

Here is the code of the referred answer:这是参考答案的代码:

import time
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
line, = ax.plot(np.random.randn(100))

fig.canvas.draw()
plt.show(block=False)


tstart = time.time()
num_plots = 0
while time.time()-tstart < 5:
    line.set_ydata(np.random.randn(100))
    ax.draw_artist(ax.patch)
    ax.draw_artist(line)
    fig.canvas.blit(ax.bbox)
    fig.canvas.flush_events()
    num_plots += 1
print(num_plots/5)

To have my perfect solution I need to also update the title of the plot besides the lines.为了获得完美的解决方案,除了行之外,我还需要更新 plot 的标题 For example I would like to print the iteration number (or some counter for the loop) in the title of the figure.例如,我想在图的标题中打印迭代编号(或循环的一些计数器)。

How to do this?这个怎么做?

I tried updating the title of the figure inside the while loop, but the title prints the first value of num_plots and then the last one, nothing in between.我尝试在 while 循环中更新图形的标题,但标题会打印 num_plots 的第一个值,然后是最后一个值,中间没有任何内容。 More specifically, I added更具体地说,我添加了

ax.set_title('num_plots = ' + str(num_plots))

as the last line inside the while loop, and it results in this behavior where you can see the title is only updated at the end of the loop (even when the instruction is inside it): click here to see the animated gif作为 while 循环内的最后一行,它会导致这种行为,您可以看到标题仅在循环结束时更新(即使指令在其中):单击此处查看动画 gif

You can set the string in the text object returned by title , just like you set the ydata in the line object returned by plot:您可以在title返回的文本 object 中设置字符串,就像在 plot 返回的行 object 中设置 ydata 一样:

titl = ax.set_title('')
while time.time()-tstart < 5:
   ...
   titl.set_text(f'num_plots = {num_plots}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM