import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
# 초기값 설정
a_init = 1
b_init = 0
c_init = 0
d_init = 0
# 3차 함수 그래프를 그리는 함수
def update(val):
a = s_a.val
b = s_b.val
c = s_c.val
d = s_d.val
y = a * x**3 + b * x**2 + c * x + d
ax.clear()
ax.plot(x, y, label=f"${a}x^3 + {b}x^2 + {c}x + {d}$")
ax.set_title('Cubic Function')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
ax.axhline(0, color='black',linewidth=1)
ax.axvline(0, color='black',linewidth=1)
ax.legend()
plt.draw()
# x 범위 설정
x = np.linspace(-10, 10, 400)
# 그래프 및 슬라이더 설정
fig, ax = plt.subplots(figsize=(8, 6))
plt.subplots_adjust(left=0.1, bottom=0.25)
# 초기 그래프
y = a_init * x**3 + b_init * x**2 + c_init * x + d_init
ax.plot(x, y, label=f"${a_init}x^3 + {b_init}x^2 + {c_init}x + {d_init}$")
ax.set_title('Cubic Function')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
ax.axhline(0, color='black',linewidth=1)
ax.axvline(0, color='black',linewidth=1)
ax.legend()
# 슬라이더 설정
axcolor = 'lightgoldenrodyellow'
ax_a = plt.axes([0.1, 0.1, 0.65, 0.03], facecolor=axcolor)
ax_b = plt.axes([0.1, 0.05, 0.65, 0.03], facecolor=axcolor)
ax_c = plt.axes([0.1, 0.00, 0.65, 0.03], facecolor=axcolor)
ax_d = plt.axes([0.1, -0.05, 0.65, 0.03], facecolor=axcolor)
s_a = Slider(ax_a, 'a', -10.0, 10.0, valinit=a_init)
s_b = Slider(ax_b, 'b', -10.0, 10.0, valinit=b_init)
s_c = Slider(ax_c, 'c', -10.0, 10.0, valinit=c_init)
s_d = Slider(ax_d, 'd', -10.0, 10.0, valinit=d_init)
# 슬라이더 값 변경 시 호출될 함수
s_a.on_changed(update)
s_b.on_changed(update)
s_c.on_changed(update)
s_d.on_changed(update)
plt.show()