交互式股票图表,带滑块的分步动画。 Matplotlib 和 Jupyter

Interactive Stock Chart, step by step animation with a slider. Matplolib & Jupyter

在这个 post: 中,我编写了一段代码,其中用户 Zephyr 出色地修复了使用键盘箭头交互式模拟股票的代码。
原来我在 Jupyter 中找到了使用模块 ipywidgets 做同样事情的方法。该代码有效,但不幸的是,同一张图表被绘制了两次。我不知道为什么会这样。有人可以帮忙吗?我只想显示一个图(注意第二个图在我使用滑块时不会移动)。
这是代码:

%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('all_stocks_5yr.csv')
df_apple = df[df['Name'] == 'AAPL'].copy()
df_apple['date'] = pd.to_datetime(df_apple['date'])
df_apple.reset_index(inplace = True)

bars_to_display = 60
step = widgets.IntSlider(value=0, min=0, max=len(df_apple)-bars_to_display)

val_array = []
for idx, val in df_apple.iterrows():
    val_array.append(val)
    
x = np.arange(0, len(df_apple))

fig, (ax, ax2) = plt.subplots(2, figsize = (12, 8), gridspec_kw = {'height_ratios': [4, 1]}, sharex = True)

def f(step):
    
    ax.cla()
    ax2.cla()
    
    for i in range(step, bars_to_display + step):
        
        color = '#2CA453'
        if val_array[i]['open'] > val_array[i]['close']: color = '#F04730'
        ax.plot([x[i], x[i]], [val_array[i]['low'], val_array[i]['high']], color = color)
        ax.plot([x[i], x[i] - 0.1], [val_array[i]['open'], val_array[i]['open']], color = color)
        ax.plot([x[i], x[i] + 0.1], [val_array[i]['close'], val_array[i]['close']], color = color)
        ax2.bar(x[i], val_array[i]['volume'], color = 'lightgrey')
        
    display(fig)
    

display(step)
out = widgets.interactive_output(f, {'step': step})
display(out)

行:

fig, (ax, ax2) = plt.subplots(2, figsize = (12, 8), gridspec_kw = {'height_ratios': [4, 1]}, sharex = True)

绘制第一张图。只需在之后添加 plt.close()

完整代码

from IPython.display import display
from ipywidgets import interactive, widgets
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline

df = pd.read_csv('all_stocks_5yr.csv')
df_apple = df[df['Name'] == 'AAPL'].copy()
df_apple['date'] = pd.to_datetime(df_apple['date'])
df_apple.reset_index(inplace = True)

bars_to_display = 60
step = widgets.IntSlider(value = 0, min = 0, max = len(df_apple) - bars_to_display)

val_array = []
for idx, val in df_apple.iterrows():
    val_array.append(val)

x = np.arange(0, len(df_apple))

fig, (ax, ax2) = plt.subplots(2, figsize = (12, 8), gridspec_kw = {'height_ratios': [4, 1]}, sharex = True)
plt.close()


def f(step):
    ax.cla()
    ax2.cla()

    for i in range(step, bars_to_display + step):

        color = '#2CA453'
        if val_array[i]['open'] > val_array[i]['close']: color = '#F04730'
        ax.plot([x[i], x[i]], [val_array[i]['low'], val_array[i]['high']], color = color)
        ax.plot([x[i], x[i] - 0.1], [val_array[i]['open'], val_array[i]['open']], color = color)
        ax.plot([x[i], x[i] + 0.1], [val_array[i]['close'], val_array[i]['close']], color = color)
        ax2.bar(x[i], val_array[i]['volume'], color = 'lightgrey')

    display(fig)


display(step)
out = widgets.interactive_output(f, {'step': step})
display(out)