Matplotlib animate OHLC 不刷新

Matplotlib animate OHLC does not refresh

我正在尝试构建一个图表来显示数据馈送的烛台。下面提供了代码。该图应该是动画的,但它不会更新。有人可以帮忙吗?

class Graph(object):
def __init__(self, ticker_name):
    self.datafeed = self.get_datafeed(ticker_name)
    self.figure = plt.figure()
    self.ax1 = self.figure.add_subplot(211)
    self.ax2 = self.figure.add_subplot(212)
    animation.FuncAnimation(self.figure, self.animate, interval=10000, init_func=self.init_figure)
    plt.show()

def get_datafeed(self, ticker_name):
    self.parameters = {"ticker_name": ticker_name,
                       "history": 100}
    return DataFeed(self.parameters)

def init_figure(self):
    self.ax1.xaxis.set_major_formatter(DateFormatter('%H:%M'))
    self.ax1.grid()
    self.ax2.grid()
    self.ax1.set_title(self.parameters["ticker_name"].upper())

def animate(self, i):
    time.sleep(2)
    self.datafeed.refresh()
    data = self.datafeed.query(10)
    self.ax1.clear()
    self.ax2.clear()
    self.plot_candles(data[["time", "open", "high", "low", "close"]])

def plot_candles(self, df):
    df.loc[:, "time"] = df.time.apply(date2num)
    mpf.candlestick_ohlc(self.ax1, df.values.tolist(), width=0.0005, colordown="r", colorup="g")
    self.ax1.set_ylim(df["low"].min() - 5, df["high"].max() + 5)

不要在动画中使用 time.sleep()。而是使用 FuncAnimationinterval 参数来控制更新速度。

您还需要保留对 FuncAnimation 的引用。使用

self.ani = animation.FuncAnimation( ... )

否则FuncAnimation一出图就会被垃圾回收

(注意,如果这样不能解决问题,你需要提供一个
Minimal, Complete, and Verifiable example 的问题)