Matplotlib requires careful timing? (Or is there a flag showing that the plot is made?)

The following code does not work properly:

import matplotlib.pyplot as plt plt.plot(range(100000), '.') plt.draw() ax = plt.gca() lblx = ax.get_xticklabels() lblx[1]._text = 'hello!' ax.set_xticklabels(lblx) plt.draw() plt.show() 

I get the following picture: enter image description here

I assume that the reason is that automatic xticklabels did not have time to fully create when get_xticklabels() called. And indeed by adding plt.pause(1)

 import matplotlib.pyplot as plt plt.plot(range(100000), '.') plt.draw() plt.pause(1) ax = plt.gca() lblx = ax.get_xticklabels() lblx[1]._text = 'hello!' ax.set_xticklabels(lblx) plt.draw() plt.show() 

will give the expected

enter image description here

I am not very happy with this condition (I need to manually insert delays). And my main concern: how can I find out how much time I need to wait? Of course, this depends on the number of curly elements, the strength of the machine, etc.

So my question is: is there any flag to find out that matplotlib has finished drawing all the elements? Or is there a better way to do what I do?

+5
source share
1 answer

It should be noted first that you can pause arbitrarily

 plt.pause(1e-18) 

The problem is that plt.draw() calls plt.gcf().canvas.draw_idle() . This means that the drawing is drawn at some arbitrary point, when there is time for this - therefore, _idle .

Instead, you probably want to draw a shape at a specific point in the code that you need.

 plt.gcf().canvas.draw() 

Full code:

 import matplotlib.pyplot as plt plt.plot(range(100000), '.') plt.gcf().canvas.draw() ax = plt.gca() lblx = ax.get_xticklabels() lblx[1]._text = 'hello!' ax.set_xticklabels(lblx) plt.show() 
+3
source

Source: https://habr.com/ru/post/1275449/


All Articles