更改matplotlib.pyplot text()对象属性

2024-04-26 13:20:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个matplotlib.pyplot图,它在循环中更新以创建动画,使用我从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)

现在我想在图上画一个plt.text(),它将显示已经过去的时间。然而,将plt.text()语句放入循环中,在每个迭代的处创建一个新的text对象,将它们放在彼此之上。所以我必须在第一次迭代中只创建一个text对象,然后在随后的迭代中修改它。不幸的是,我在任何文档中都找不到如何修改这个对象的实例(它是一个matplotlib.text.Text对象)的属性。有什么帮助吗?


Tags: 对象代码textanswerimportnewmatplotlibanother
2条回答
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)

注意plt.cla()调用。它会清除屏幕。

set_data类似,您可以使用set_text(参见此处的文档:http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.text.Text.set_text)。

所以首先

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

然后在循环中:

text.set_text("Some other text")

在您的示例中,它可能看起来像:

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)

相关问题 更多 >