我想找到一個二次方程的兩個根,ax^2 bx c =0并將它們與系數作圖,c同時保持a為可變引數。要更改a并查看更改引數的圖會發生什么,我想從 Python 的 Matplotlib 模塊創建一個Silderfor 。a
我有以下內容,但是,它似乎不起作用。
# Solve the quadratic equation ax**2 bx c = 0
from matplotlib.widgets import Slider # import the Slider widget
import numpy as np
import matplotlib.pyplot as plt
import cmath
a_min = -2
a_max = 2
a_init = -2
fig = plt.figure(figsize=(8,3))
# Slider layout
slider_ax = plt.axes([0.1, 0.05, 0.8, 0.05])
b = 10
def sol1(a,b,c):
d = (b**2) - (4*a*c) # Discriminant
return (-b-np.sqrt(d))/(2*a)
def sol2(a,b,c):
d = (b**2) - (4*a*c) # Discriminant
return (-b np.sqrt(d))/(2*a)
for c in np.linspace(-2, 2, 11):
print('c=',c,' sol1=',sol1(a_init,b,c),' sol2=',sol2(a_init,b,c))
# Plot with initial parameter value
#plt.axes(func_ax)
plt.xlabel('$c$')
plt.title('Roots of $ax^2 bx c = 0$')
plot1, = plt.plot(c, sol1(a_init,b,c), 'r')
plot2, = plt.plot(c, sol2(a_init,b,c), 'b')
# Create a slider
a_slider = Slider(slider_ax, # the axes object containing the slider
'$a$', # the name of the slider parameter
a_min, # minimal value of the parameter
a_max, # maximal value of the parameter
valinit=a_init # initial value of the parameter
)
# Update function
def update(a):
plot1.set_ydata(sol1(a,b,c))
plot2.set_ydata(sol2(a,b,c))
fig.canvas.draw_idle() # redraw the plot
# Execute when parameter gets updated
a_slider.on_changed(update)
plt.show()
有什么幫助嗎?
uj5u.com熱心網友回復:
我對您的代碼進行了一些修改以使滑塊作業:
- 首先,
plot1在plot2代碼中的回圈中定義。這意味著它們會在每次迭代中被洗掉并再次創建。相反,計算要繪制的所有變數然后在回圈外繪制它們更有意義。這是在update_sols函式中執行的。 - 其次,我改變了
update你的滑塊的功能。滑塊更新的變數應該通過使用來訪問(參見
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/415771.html標籤:
上一篇:在matplotlib中疊加imshow和scatter時,set_position和set_size_inches無法正常作業
