1

I'm trying to make the interactive histogram but during

update old histogram is not been cleared, as shown in the image below.

enter image description here)

above plot is generated using following code

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

1 Answer 1

3

ax.hist is returning a tuple containing the number of bins, the edges of the bins and then the patches... you thus need to capture the patches and remove them in update.

You need to use t.remove() in update, as in:

*_, 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()
Sign up to request clarification or add additional context in comments.

7 Comments

if i do that AttributeError: 'tuple' object has no attribute 'remove'', problem is t is a tuple and remove is not available.
haha, my mistake, ax.hist() is returning a tuple, which yeah, is the problem.
I got the inside scoop it seams. Does the above work for you?
ya found out this post stackoverflow.com/questions/40409977/… i guess yours works too
shame, looks like this'll be marked as a duplicate I guess. Also You really should turn t into a data class :P
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.