matplotlib.widgets.Slider 带直方图

matplotlib.widgets.Slider with histogram

我正在尝试制作交互式直方图,但是在

更新旧直方图未清除,如下图

)

上图是使用以下代码生成的

from functools import lru_cache
import scipy.stats as ss
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

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

weight = ss.lognorm(0.23, 0, 70.8)

@lru_cache
def sampling(n):
    return [ weight.rvs().mean() for i in range(1000) ]

theme = {
    'color' : "#1f77b4",
    'alpha' : 0.7,
}

t = ax.hist(sampling(100), **theme)

slider = widgets.Slider(
    ax      = plt.axes([0.25, 0.1, 0.5, 0.03]),
    label   = "n",
    valmin  = 10,
    valmax  = 1000,
    valinit = 100,
    valstep = 1

def update(val):
    global t
    del t
    t = ax.hist(sampling(int(val)), **theme)
    fig.canvas.draw_idle()

slider.on_changed(update)
ax.set_title('Distribution of Sample Size Mean')
plt.show()

ax.hist 正在返回一个元组,其中包含垃圾箱的数量、垃圾箱的边缘,然后是补丁……因此您需要捕获补丁并在更新中删除它们。

您需要在 update 中使用 t.remove(),如:

*_, patches = ax.hist()

def update(val):
    global patches
    for p in patches:
        p.remove()

    *_, patches = ax.hist(sampling(int(val)), **theme)
    fig.canvas.draw_idle()