Home > Net >  Disable constant position reset of Matplotlib chart
Disable constant position reset of Matplotlib chart

Time:10-19

I have a python code that by using Matplotlib displays a candlestick chart real time, so the last bar updates each second, the problem Is that the program doesn't let me scroll back/zoom in ... (interacting with the chart) because It keeps reset the position. How can I solve this? Thanks, have a good day.

import pandas as pd
import mplfinance as mpf
import matplotlib.animation as animation

# Class to simulate getting more data from API:


class RealTimeAPI():
    def __init__(self):
    self.data_pointer = 0
    self.data_frame = pd.read_csv('SP500_NOV2019_IDay.csv', 
    index_col=0, parse_dates=True)
    # self.data_frame = self.data_frame.iloc[0:120,:]
    self.df_len = len(self.data_frame)

def fetch_next(self):
    r1 = self.data_pointer
    self.data_pointer  = 1
    if self.data_pointer >= self.df_len:
        return None
    return self.data_frame.iloc[r1:self.data_pointer, :]

def initial_fetch(self):
    if self.data_pointer > 0:
        return
    r1 = self.data_pointer
    self.data_pointer  = int(0.2*self.df_len)
    return self.data_frame.iloc[r1:self.data_pointer, :]


rtapi = RealTimeAPI()

resample_map = {'Open': 'first',
            'High': 'max',
            'Low': 'min',
            'Close': 'last'}
resample_period = '15T'

df = rtapi.initial_fetch()
rs = df.resample(resample_period).agg(resample_map).dropna()

fig, axes = mpf.plot(rs, returnfig=True, figsize=(11, 8), 
type='candle', title='\n\nGrowing Candle')
ax = axes[0]


def animate(ival):
   global df
   global rs
   nxt = rtapi.fetch_next()
   if nxt is None:
       print('no more data to plot')
       ani.event_source.interval *= 3
       if ani.event_source.interval > 12000:
           exit()
       return
   df = df.append(nxt)
   rs = df.resample(resample_period).agg(resample_map).dropna()
   ax.clear()
   mpf.plot(rs, ax=ax, type='candle')

ani = animation.FuncAnimation(fig, animate, interval=250)
mpf.show()

CodePudding user response:

The code you have posted is the "growing candle animation" example from the mplfinance repository. Mplfinance does not use Matlab but rather MatPlotLib.

(It is temping to edit your question and change all references of "Matlab" to "Mplfinance/Matplotlib" but I will leave that to you to do, just in case I'm missing something or you are actually doing something with Matlab. Furthermore, just to be clear, the code is plotting a "candlestick chart," not a "bar chart." By the way, MatPlotLib was originally written to somewhat resemble the Matlab plotting interface, so some confusion is understandable, but matplotlib has since grown in many ways).

The comment by @CrisLuengo is correct in that the mplfinance code is re-drawing the plot more-or-less from scratch with each animation frame, so any interactive changes (such as zooming in) will be re-set with each animation frame. The mplfinance animation examples do this to keep the code simpler.

I believe it is possible to accomplish what you want (animation with interactivity) however I've never done it myself, so without being explicit as to how to do it, if I were going to do so, I would probably do something along the lines of the following posts:

Full disclosure: I am the maintainer of the mplfinance package. Perhaps someday we will enhance mplfinance to make this easier; but for now such an enhancement is not a priority; therefore one of the above more complex solutions is necessary.

  • Related