[英]How to get radio buttons to update histogram Matplotlib Python
I have a hard time getting radio buttons to update the histogram when using matplotlib.animation.使用 matplotlib.animation 时,我很难获得单选按钮来更新直方图。
I'd like to show random sampling from a normal distribution.我想展示来自正态分布的随机抽样。 It starts with n=20.它从 n=20 开始。 The animation works for n = 20. The radio buttons add a few more options: n=50, n=100, n=200. animation 适用于 n = 20。单选按钮添加了更多选项:n=50、n=100、n=200。
Below are my codes.以下是我的代码。 Thank you for your help!谢谢您的帮助!
%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()
The code is adapted from this answer .代码改编自这个答案。 For some reason you always have to click twice before the figure updates, but otherwise it should work fine.出于某种原因,您必须在图形更新之前单击两次,否则它应该可以正常工作。
# %matplotlib widget # for jupyter notebook
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
from matplotlib.animation import FuncAnimation
import numpy as np
n_max = 200
x_curr = np.random.normal(-2.5, 1, size=n_max)
bins = np.arange(-4, 4, 0.5)
def animate(i):
ax.clear()
ax.set_title('Sampling the Normal Distribution')
ax.set_ylabel('Frequency')
ax.set_xlabel('Value')
ax.annotate('n = {}'.format(i), [3, 25])
ax.axis([-7, 5, 0, 30])
ax.hist(x_curr[:i], bins=bins)
anis = []
def on_click(event):
n = int(event[2:])
for ani in anis:
ani.event_source.stop()
anis.remove(ani)
del ani
print(n)
ani = FuncAnimation(fig, animate, frames=n, repeat=False)
anis.append(ani)
fig.canvas.draw_idle()
fig = plt.figure()
ax = fig.subplots()
rax = plt.axes([0.01, 0.2, 0.15, 0.25])
radio = RadioButtons(rax, ('n=20', 'n=50', 'n=100', 'n=200'))
radio.on_clicked(on_click)
animate(20)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.