我只是想使用 matplotlib 制作一個實時圖表。但是我找不到繪制-洗掉-重繪 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 軸值。然而,水平線不會消失。
uj5u.com熱心網友回復:
在您的代碼中,這是:
plt.axhline(y = ys[-2], linewidth=2, color='r', linestyle='-').remove()
不洗掉前一個axhline;它添加一個新axhline的 aty=ys[-2]然后立即將其洗掉。所以,它實際上什么也沒做。
您必須洗掉您插入的同一行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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532768.html
標籤:Pythonmatplotlibmatplotlib-动画实时图
