Unable to refresh plt.axhline() in matplotlib

Question:

I’m just trying to make a live graph using matplotlib.However I couldn’t find a way to draw-remove-redraw axhline(). My aim is to show a horizontal line of newest value of Y axis values and of course remove the recent horizontal line.

`

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()

`

expecting that to only show the newest y axis values with a horizontal line. However horizontal lines doesn’t vanish away.

Asked By: enis

||

Answers:

In your code, this:

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

doesn’t remove the previous axhline; it adds a new axhline at y=ys[-2] and then immediately removes it. So, it effectively does nothing.

You have to remove the same line you inserted with plt.axhline. Save the object returned by this function somewhere, and remove it when the next frame is animated.

Here’s a solution with a bit of default mutable argument abuse.

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()
Answered By: tfpf