Change object properties matplotlib.pyplot text ()

I have a matplotlib.pyplot graph that updates a loop to create an animation using this code, which I got from another answer :

 import matplotlib.pyplot as plt fig, ax = plt.subplots() x = [1, 2, 3, 4] #x-coordinates y = [5, 6, 7, 8] #y-coordinates for t in range(10): if t == 0: points, = ax.plot(x, y, marker='o', linestyle='None') else: new_x = ... # x updated new_y = ... # y updated points.set_data(new_x, new_y) plt.pause(0.5) 

Now I want to put plt.text() on a plot that shows the elapsed time. However, adding the plt.text() operator inside the loop creates a new text object at each iteration, placing them on top of each other. Therefore, I have to create only one text object in the first iteration, and then change it in subsequent iterations. Unfortunately, I cannot find in any documentation how to change the properties of an instance of this object (this is a matplotlib.text.Text object) after its creation. Any help?

+4
source share
2 answers

Like set_data you can use set_text (see the documentation here: http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.text.Text.set_text ).

So first

 text = plt.text(x, y, "Some text") 

and then in the loop:

 text.set_text("Some other text") 

In your example, it might look like this:

 for t in range(10): if t == 0: points, = ax.plot(x, y, marker='o', linestyle='None') text = plt.text(1, 5, "Loops passed: 0") else: new_x = ... # x updated new_y = ... # y updated points.set_data(new_x, new_y) text.set_text("Loops passed: {0}".format(t)) plt.pause(0.5) 
+10
source
 import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = [1, 2, 3, 4] y = [5, 6, 7, 8] for t in range(10): plt.cla() plt.text(4.6,6.7,t) x = np.random.randint(10, size=5) y = np.random.randint(10, size=5) points, = ax.plot(x, y, marker='o', linestyle='None') ax.set_xlim(0, 10) ax.set_ylim(0, 10) plt.pause(0.5) 

Note the call to plt.cla() . He clears the screen.

0
source

All Articles