[英]How to get radio buttons to update histogram Matplotlib Python
使用 matplotlib.animation 時,我很難獲得單選按鈕來更新直方圖。
我想展示來自正態分布的隨機抽樣。 它從 n=20 開始。 animation 適用於 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()
代碼改編自這個答案。 出於某種原因,您必須在圖形更新之前單擊兩次,否則它應該可以正常工作。
# %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.