ghost  tang
ghost tang

Reputation: 33

Python updating histogram with random generate integers

I am new to python and want to develop a histogram that update a list of 20 random integers from 0-10; but the histogram's bars don't match x-axis's value and only have 10 bars. while there are also some other bars appear in the background constantly other than the updating blue bars. What seem to be the issue? Thanks!

import matplotlib 
matplotlib.use('TkAgg')
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
stat_num =20
range_num=10
y_lim=10

def animate(frameno):
    x = [random.randint(0, range_num) for _ in range(stat_num)]
    n, bins, ignored = plt.hist(x,stat_num)
    axes = plt.gca()
    axes.set_ylim([0,y_lim])
    for rect, h in zip(patches, n):
        rect.set_height(h)
    return patches    


fig, ax = plt.subplots()
x = [random.randint(0, range_num) for _ in range(stat_num)]
print(x)
n, bins, patches = plt.hist(x,stat_num)
axes = plt.gca()
axes.set_ylim([0,y_lim])

ani = animation.FuncAnimation(fig, animate, blit=True, interval=100,
                          repeat=True)
plt.show()

enter image description here

Upvotes: 0

Views: 844

Answers (1)

Pierre de Buyl
Pierre de Buyl

Reputation: 7293

  1. You need to fix the bins yourself, via the option bins=np.linspace(0, 10, 11) that will use equispaced integer bins.
  2. A single plt.hist command is enough. You can update then the existing graphic using NumPy's histogram command.

I tested the following:

import matplotlib 
matplotlib.use('TkAgg')
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

stat_num =20
range_num=10
y_lim=10

fig, ax = plt.subplots()
x = [random.randint(0, range_num) for _ in range(stat_num)]

print(x)
n, bins, patches = plt.hist(x, bins=np.linspace(0, 10, 11))

def animate(frameno):
    x = [random.randint(0, range_num) for _ in range(stat_num)]
    n, bins = np.histogram(x, bins=np.linspace(0, 10, 11))
    for rect, h in zip(patches, n):
        rect.set_height(h)
    return patches

axes = plt.gca()

axes.set_ylim([0,y_lim])

ani = animation.FuncAnimation(fig, animate, blit=True, interval=100,
                              repeat=True)

plt.show()

Upvotes: 1

Related Questions