无法刷新matplotlib中的plt.axhline()

k4emjkb1  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(145)

我只是想用matplotlib制作一个实时的图表。但是我找不到draw-remove-redraw axhline()的方法。我的目标是显示一条水平线的最新值的Y轴值,当然,删除最近的水平线。
`

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import time
from random import randrange

style.use("fivethirtyeight")

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
#ax1 = plt.subplot()
second = 1

xs = list()
ys = list()
ann_list = []
a = 0
ten = 10

def animate(i):
    global second
    global a, ten

    random = randrange(ten)
    ys.append(random)
    xs.append(second)
    second += 1

    ax1.plot(xs, ys, linestyle='--', marker='o', color='b')


    plt.axhline(y = ys[-1], linewidth=2, color='r', linestyle='-')
    if len(xs) > 2:
        plt.axhline(y = ys[-2], linewidth=2, color='r', linestyle='-').remove()


    if len(ys) > 20 and len(xs) > 20:
        ax1.lines.pop(0)
        ys.pop(0)
        xs.pop(0)
        a += 1

    ax1.set_xlim(a, (21 + a))
    # ax1.set_ylim(0, 200)

ani = animation.FuncAnimation(fig, animate, interval=100)

plt.show()

`
期望它只显示最新的y轴值和一条水平线。但是水平线并没有消失。

gojuced7

gojuced71#

在您的程式码中:

plt.axhline(y = ys[-2], linewidth=2, color='r', linestyle='-').remove()

不会删除之前的axhline;它在y=ys[-2]处添加一个新的axhline,然后立即删除它。
您必须删除使用plt.axhline插入的同一行。将此函数返回的对象保存到某个位置,并在下一帧动画显示时删除它。
这里有一个解决方案,其中有一些默认的可变参数滥用。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import time
from random import randrange

style.use("fivethirtyeight")

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
second = 1

xs = list()
ys = list()
ann_list = []
a = 0
ten = 10

def animate(i, prev_axhline=[]):
    global second
    global a, ten

    random = randrange(ten)
    ys.append(random)
    xs.append(second)
    second += 1

    ax1.plot(xs, ys, linestyle='--', marker='o', color='b')


    if prev_axhline:
        prev_axhline.pop().remove()
    prev_axhline.append(plt.axhline(y = ys[-1], linewidth=2, color='r', linestyle='-'))


    if len(ys) > 20 and len(xs) > 20:
        ax1.lines.pop(0)
        ys.pop(0)
        xs.pop(0)
        a += 1

    ax1.set_xlim(a, (21 + a))
    # ax1.set_ylim(0, 200)

ani = animation.FuncAnimation(fig, animate, interval=100)

plt.show()

相关问题