0
我需要製作一些具有多個參數的圖,我選擇使它與matplotlib滑塊更具互動性。對於我在實際工作之前的一些練習,我試圖讓它變得相當簡單,但我的滑塊不起作用。這是代碼,這是從here的啓發。Martplotlib滑塊不起作用
代碼:
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
。
很好的答案,但我可以問一下p1,= ***和p1 = ***之間的區別是什麼?逗號是做什麼的? – Bobesh
@Bobesh它允許將結果賦值給一個元組(請參閱此問題:[Python代碼。它是逗號運算符嗎?](http://stackoverflow.com/questions/16037494/python-code-is-it-comma-operator ) – user2314737