使用 matplotlib 滑块进行动态绘图
我想在 matplotlib Slider 的帮助下制作动态图。我的函数获取用于绘制 beta 分布函数的 a、b 值数组,并且滑块中的每个值应使用新的 a、b 值更新绘图。 这是我的代码。
def plot_dynamic_beta(a_b_list: np.array, label_name: str):
def update(val):
timestamp = time_slider.val
a, b = a_b_list[timestamp] # new a, b values to draw the new distribution
rv = beta(a, b)
Plot.set_ydata(rv.pdf(np.linspace(0, 1, 100))) # i guess here is the wrong part
plt.draw()
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
rv = beta(1, 1)
Plot, = plt.plot(rv.pdf(np.linspace(0, 1, 100)), 'k-', lw=2, label=label_name)
plt.axis([0, 1, -10, 10])
# slider_x = np.arange(0, len(a_b_list))
slider_x = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
time_slider = Slider(slider_x, 'timepoint',
0, len(a_b_list) - 1, valinit=0, valstep=np.arange(0, len(a_b_list)))
time_slider.on_changed(update)
plt.show()
所以它正确地绘制了第一个图,但更改滑块值并没有绘制出我需要的内容。示例 a_b_list= np.array([(1,2),(2,2),(3,2),(4,2)]) 当我更改滑块值时,它不会使用我给出的 a、b 值绘制 beta 分布。例如,如果我将幻灯片更改为 2,它应该绘制 a=3 和 b=2 的 beta 分布,但它不会这样做。 我做错了什么?
I want to make a dynamic plot with the help of matplotlib Slider. My function gets an array of a, b values for plotting beta distribution functions, and each value from slider should update the plot with the new a, b values.
Here is my code.
def plot_dynamic_beta(a_b_list: np.array, label_name: str):
def update(val):
timestamp = time_slider.val
a, b = a_b_list[timestamp] # new a, b values to draw the new distribution
rv = beta(a, b)
Plot.set_ydata(rv.pdf(np.linspace(0, 1, 100))) # i guess here is the wrong part
plt.draw()
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
rv = beta(1, 1)
Plot, = plt.plot(rv.pdf(np.linspace(0, 1, 100)), 'k-', lw=2, label=label_name)
plt.axis([0, 1, -10, 10])
# slider_x = np.arange(0, len(a_b_list))
slider_x = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
time_slider = Slider(slider_x, 'timepoint',
0, len(a_b_list) - 1, valinit=0, valstep=np.arange(0, len(a_b_list)))
time_slider.on_changed(update)
plt.show()
so it plots the first plot correctly but changing the slider value doesn't plot what I need. Example a_b_list= np.array([(1,2),(2,2),(3,2),(4,2)])
When I change the slider value it doesn't plot the beta distribution with the a,b values I gave. So for example if I change the slide to 2 it should plot beta distribution with a=3 and b=2 but it doesn't do it.
What did I do wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经绘制了它。这是我的代码,以获取问题中描述的图。
I have got it with plotly. Here is my code to get a plot described in the question.