【问题标题】:matplotlib.widgets.Slider with histogrammatplotlib.widgets.Slider 带直方图
【发布时间】:2020-05-28 10:01:31
【问题描述】:

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

更新旧直方图未被清除,如下图所示。

)

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

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()

【问题讨论】:

    标签: python matplotlib matplotlib-widget


    【解决方案1】:

    ax.hist 正在返回一个元组,其中包含 bin 的数量、bin 的边缘以及补丁...因此您需要捕获补丁并在更新时将其删除。

    你需要在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()
    

    【讨论】:

    • 如果我这样做AttributeError: 'tuple' object has no attribute 'remove'',问题是t 是一个元组并且删除不可用。
    • 哈哈,我的错,ax.hist() 正在返回一个元组,是的,这就是问题所在。
    • 我得到了内部独家新闻它的接缝。以上对你有用吗?
    • 你发现了这篇文章 stackoverflow.com/questions/40409977/… 我猜你的也可以
    • 耻辱,我猜这似乎会被标记为重复。另外你真的应该把 t 变成一个数据类:P
    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2013-09-13
    • 2014-04-10
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多