我如何使交互式滑块控制条形图中的 x 轴以显示每次更改的一部分数据

How can i make an interact Slider control the x axis in bar digram to show a part of the data with every change

当我更改滑块的值时,如何让一个交互滑块控制 x 轴一次只显示 5 个柱,图表显示接下来的五个柱等等 我曾尝试使用交互来做到这一点,但它改变了酒吧的数量 如果有人有想法,我将不胜感激 这是我尝试过的方式

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
from ipywidgets import interact 
import ipywidgets as ipw

a =[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
b =[10,11,10,12,13,11,15,12,20,9,11,12,10,18]
def func(x = 5):
    plt.bar(a[:x],b[:x])
    plt.title('graph 1')
    plt.show()

interact(f,x =ipw.IntSlider(min=1, max=14, step=1,value=10, description='Test:', disabled=False,readout_format='d'))

您可以使用 Slider 小部件,然后设置 valstep 参数来控制每次单击滑块时滑块变化的步数。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)

a =[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
b =[10,11,10,12,13,11,15,12,20,9,11,12,10,18,21]

plt.bar(a, b)

bar_number = 5

ax.set_xlim(0.5, bar_number+0.5)

# plt.axes(rect, projection=None, polar=False, **kwargs)
# rect is a 4-tuple of floats  = [left, bottom, width, height]
# A new axes is added with dimensions rect in normalized (0, 1) units using add_axes on the current figure.
# (left, bottom) specify lower left corner coordinates of the new axes in normalized (0, 1) units
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=axcolor)

# Slider(ax, label, valmin, valmax)
spos = Slider(axpos, 'Pos', 0, max(a)-bar_number, valinit=0., valstep=bar_number)

def update(val):
    pos = spos.val
    ax.set_xlim(pos+0.5, pos+0.5+bar_number)
    fig.canvas.draw_idle()

spos.on_changed(update)

plt.show()

plot screenshot嗨,非常感谢您的回答,我找到了另一种使用 interact ipywidgets 的方法

from ipywidgets import interact
import matplotlib.pyplot as plt
import ipywidgets as ipw

a = [0,1,2,3,4,5,6,7,8,9,10]
b = [2,4,2,4,3,1,5,6,1,9,3]
def f (x):
    plt.bar(a[x:x+3],b[x:x+3] ,color = 'Green')
    plt.title('graph 1')
    plt.show
interact(f,x = ipw.IntSlider(min=a[0], max=a[-3], step=1,value=a[0]))