【发布时间】:2020-07-28 06:54:27
【问题描述】:
在使用 matplotlib.animation 时,我很难获得单选按钮来更新直方图。
我想展示来自正态分布的随机抽样。它从 n=20 开始。动画适用于 n = 20。单选按钮添加了更多选项:n=50、n=100、n=200。
以下是我的代码。感谢您的帮助!
%matplotlib notebook
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
n = 20
x = np.random.normal(-2.5, 1,size=n)
# create the function that will do the plotting, where curr is the current frame
def update(curr):
# check if animation is at the last frame, and if so, stop the animation a
if curr == n:
a.event_source.stop()
plt.cla()
bins = np.arange(-4, 4, 0.5)
plt.hist(x[:curr], bins=bins)
plt.axis([-7,5,0,30])
plt.gca().set_title('Sampling the Normal Distribution')
plt.gca().set_ylabel('Frequency')
plt.gca().set_xlabel('Value')
plt.annotate('n = {}'.format(curr), [3,25])
#Plot
fig = plt.figure()
#Create radio button
rax = plt.axes([0.01, 0.2, 0.15, 0.15])
radio = RadioButtons(rax, ('n=50', 'n=100', 'n=200'))
def samplesize(label):
if label == 50:
n=50
a=animation.FuncAnimation(fig, update, interval=100)
elif label == 100:
n=100
a=animation.FuncAnimation(fig, update, interval=100)
else:
n=200
a=animation.FuncAnimation(fig, update, interval=100)
plt.draw()
radio.on_clicked(samplesize)
a = animation.FuncAnimation(fig, update, interval=100)
aax = plt.axes([0.3, 0.1, 0.6, 0.6])
plt.show()
【问题讨论】:
-
我的回答对你有用吗?
-
我无法让它在 Jupyter Notebook 上运行。感谢您的帮助!
-
您收到错误消息吗?或者它不是交互式的?确保在笔记本的开头包含
%matplotlib widget(您需要安装ipympl)。 -
当我使用我的课堂 jupyter 笔记本时,我没有收到错误,它没有显示图表或任何东西。我在我的桌面上尝试过,当我注释掉 %matplotlib 小部件时它工作了。
-
您的代码是否显示了情节?我安装了
python3.7.7和matplotlib3.2.2,对我来说,它既适用于jupyter 笔记本,也适用于普通脚本。尝试将所有动画部分注释掉,然后绘制一个空图,然后逐步添加其他功能以查看它在哪里中断。
标签: python matplotlib animation histogram