fit_curve2.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """Create slider that changes the value of the k parameter in the function."""
  2. import numpy as np
  3. from vedo.pyplot import plot
  4. from vedo import settings, Line, Text2D, Plotter
  5. settings.default_font = "Brachium"
  6. settings.remember_last_figure_format = True
  7. def func(x, h, a, x0, k):
  8. return h + a * (x-x0) * np.sin((x-x0)**2 / k)
  9. def callback(w, e):
  10. y = func(xdata, *true_params[:3], slider.value)
  11. res = np.sum((ydata - y)**2 / 100)
  12. txt2d.text(f"Residuals: {res:.3f}")
  13. # remove previous fit line and insert the new one
  14. line = Line(np.c_[xdata, y], c="green4", lw=3)
  15. p.remove(p[2]).insert(line)
  16. true_params = [20, 2, 8, 3]
  17. xdata = np.linspace(3, 10, 100)
  18. ydata_true = func(xdata, *true_params)
  19. ydata = np.random.normal(ydata_true, 3, 100)
  20. p = plot(
  21. xdata,
  22. ydata,
  23. "o",
  24. mc="blue2",
  25. title="f = h + a*(x-x_0 )*sin((x-x_0 )**2 /k)",
  26. label="Data",
  27. )
  28. p += plot(xdata, ydata_true, "-g", lw=2, label="Fit")
  29. p.add_legend(pos="top-right")
  30. txt2d = Text2D(pos="bottom-left", bg='yellow5', s=1.2)
  31. plt = Plotter(size=(900, 650))
  32. slider = plt.add_slider(callback, 1, 5, value=3, title="k-value")
  33. plt.show(p, txt2d, __doc__, zoom=1.3, mode="2d")