Stefano Fedele - 4 months ago 24

Python Question

I am used to work with plots that change over the time in order to show differences when a parameter is changed. Here I provide an easy example

`import matplotlib.pyplot as plt`

import numpy as np

fig = plt.figure()

ax = fig.add_subplot(111)

ax.grid(True)

x = np.arange(-3, 3, 0.01)

for j in range(1, 15):

y = np.sin(np.pi*x*j) / (np.pi*x*j)

line, = ax.plot(x, y)

plt.draw()

plt.pause(0.5)

line.remove()

You can clearly see that increasing the paramter j the plot becames narrower and narrower.

Now if I want to do the some job with a counter plot than I just have to remove the comma after "line". From my understanding this little modification comes from the fact that the counter plot is not an element of a tuple anymore, but just an attribute as the counter plot completely "fill up" all the space available.

But it looks like there is no way to remove (and plot again) an histogram. Infact if type

`import matplotlib.pyplot as plt`

import numpy as np

fig = plt.figure()

ax = fig.add_subplot(111)

ax.grid(True)

x = np.random.randn(100)

for j in range(15):

hist, = ax.hist(x, 40)*j

plt.draw()

plt.pause(0.5)

hist.remove()

It doesn't matter whether I type that comma or not, I just get a message of error.

Could you help me with this, please?

Answer

`ax.hist`

doesn't return what you think it does.

The returns section of the docstring of `hist`

(access via `ax.hist?`

in an ipython shell) states:

```
Returns
-------
n : array or list of arrays
The values of the histogram bins. See **normed** and **weights**
for a description of the possible semantics. If input **x** is an
array, then this is an array of length **nbins**. If input is a
sequence arrays ``[data1, data2,..]``, then this is a list of
arrays with the values of the histograms for each of the arrays
in the same order.
bins : array
The edges of the bins. Length nbins + 1 (nbins left edges and right
edge of last bin). Always a single array even when multiple data
sets are passed in.
patches : list or list of lists
Silent list of individual patches used to create the histogram
or list of such list if multiple input datasets.
```

So you need to unpack your output:

```
counts, bins, bars = ax.hist(x, 40)*j
_ = [b.remove() for b in bars]
```