Python使用随机生成整数更新直方图

时间:2018-02-06 19:48:09

标签: python matplotlib

我是python的新手,想要开发一个直方图来更新0-10的20个随机整数列表;但直方图的条形与x轴的值不匹配,只有10条。虽然除了更新蓝色条之外,还有一些其他条形图出现在背景中。似乎是什么问题?谢谢!

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

1 个答案:

答案 0 :(得分:0)

  1. 您需要通过使用等间隔整数分档的选项bins=np.linspace(0, 10, 11)自行修复分档。
  2. 单个plt.hist命令就足够了。您可以使用NumPy的直方图命令更新现有图形。
  3. 我测试了以下内容:

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