我需要制作一些包含多个参数的图表,我选择使用matplotlib滑块使其更具交互性。对于我的实际任务之前的一些练习,我试图使它相对简单,但我的滑块不起作用。以下是代码,其灵感来自here。
代码:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.widgets as mw
from scipy import stats
mu = 1
sigma = 3
a = 2
b = 3
axis_color = 'lightgoldenrodyellow'
x = [i for i in range(-100,100,1)]
normal_pdf = stats.norm.pdf(x, mu, sigma)
a_normal_pdf = [i*a for i in normal_pdf]
ab_normal_pdf = [i*b*a for i in normal_pdf]
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax4.axis('off')
#sliders
a_slider_ax = fig.add_axes([0.6, 0.25, 0.25, 0.03], axisbg=axis_color)
a_slider = mw.Slider(a_slider_ax, 'a', 1, 100, valinit = a)
b_slider_ax = fig.add_axes([0.6, 0.4, 0.25, .03], axisbg = axis_color)
b_slider = mw.Slider(b_slider_ax, 'b', 1, 100, valinit = b)
#function for sliders
def sliders_on_change(val):
a_normal_pdf.set_ydata([x*a_slider for x in normal_pdf])
ab_normal_pdf.set_ydata([x*a_slider*b_slider for x in normal_pdf])
fig.canvas.draw_idle()
a_slider.on_changed(sliders_on_change)
b_slider.on_changed(sliders_on_change)
ax1.plot(x, normal_pdf, 'r-')
ax2.plot(x, a_normal_pdf, 'bo')
ax3.plot(x, ab_normal_pdf, 'g*')
plt.show()
我不完全理解幻灯片应该如何工作,所以它可能是问题而不是here的空闲问题,因为我在spyder和jupyter中尝试过它,没有区别。我可以使用滑块移动,但我无法更改a_normal_pdf
或ab_normal_pdf
。
答案 0 :(得分:1)
您的代码中有两个问题:
使用滑块对象a_slider
代替滑块的当前值a_slider.val
方法set_ydata
更改Line2D
绘图对象的y数据(我将其保存在变量p1
中以便能够修改它)
修改后的代码(希望这有帮助)
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.widgets as mw
from scipy import stats
mu = 1
sigma = 3
a = 2
b = 3
axis_color = 'lightgoldenrodyellow'
x = [i for i in range(-100,100,1)]
normal_pdf = stats.norm.pdf(x, mu, sigma)
a_normal_pdf = [i*a for i in normal_pdf]
ab_normal_pdf = [i*b*a for i in normal_pdf]
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax4.axis('off')
#sliders
a_slider_ax = fig.add_axes([0.6, 0.25, 0.25, 0.03], axisbg=axis_color)
a_slider = mw.Slider(a_slider_ax, 'a', 1, 100, valinit = a)
b_slider_ax = fig.add_axes([0.6, 0.4, 0.25, .03], axisbg = axis_color)
b_slider = mw.Slider(b_slider_ax, 'b', 1, 100, valinit = b)
#function for sliders
def sliders_on_change(val):
p1.set_ydata([x*a_slider.val for x in normal_pdf])
p2.set_ydata([x*a_slider.val*b_slider.val for x in normal_pdf])
fig.canvas.draw_idle()
a_slider.on_changed(sliders_on_change)
b_slider.on_changed(sliders_on_change)
p1,=ax1.plot(x, normal_pdf, 'r-')
p2,=ax2.plot(x, a_normal_pdf, 'bo')
p3,=ax3.plot(x, ab_normal_pdf, 'g*')
plt.show()