test_interactive_plotxy2.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Create an interactive plot that allows the user to control a parameter using a slider,
  2. The plot shows the solution to a system of equations for y given x and a constant C.
  3. The user can change the value of C using a slider, and the plot will update the y-range."""
  4. import numpy as np
  5. from scipy.optimize import fsolve
  6. from vedo import Plotter, settings
  7. from vedo.pyplot import plot
  8. # Initial values
  9. C_init = 0
  10. xdata = np.linspace(-3, 3, 50)
  11. # Function to solve for y given x and C (from your first script)
  12. def solve_for_y(x, C):
  13. y_vals = []
  14. for sign in [1, -1]: # Solve for positive and negative y
  15. def equation(y):
  16. return 0.5 * y**2 + np.log(np.abs(y)) - 0.5 * x**2 - C
  17. y_initial_guess = sign * np.exp(-0.5 * x**2 - C)
  18. root = fsolve(equation, y_initial_guess)[0]
  19. if equation(root) < 1e-5: # Only accept the root if it's a valid solution
  20. y_vals.append(root)
  21. return y_vals
  22. # Generate the y values for plotting (positive and negative y)
  23. def generate_y_values(x_values, C):
  24. y_positive = []
  25. y_negative = []
  26. for x in x_values:
  27. y_vals = solve_for_y(x, C)
  28. if len(y_vals) > 0:
  29. y_positive.append(max(y_vals)) # Choose the largest root as positive
  30. y_negative.append(min(y_vals)) # Choose the smallest root as negative
  31. else:
  32. y_positive.append(np.nan) # Use NaN for missing values
  33. y_negative.append(np.nan)
  34. return y_positive, y_negative
  35. # Function to update the plot when the slider changes
  36. def update_plot(widget=None, event=""):
  37. C_value = C_init if widget is None else widget.value
  38. y_positive, y_negative = generate_y_values(xdata, C_value)
  39. m = max(max(y_positive), abs(min(y_negative)))
  40. p = plot(xdata, y_positive, c='red5', lw=4, ylim=(-m, m))
  41. p += plot(xdata, y_negative, c='blue5', lw=4, like=p)
  42. plt.remove("PlotXY").add(p)
  43. # Create Plotter and the slider to control the value of C
  44. settings.default_font = "Brachium"
  45. plt = Plotter(size=(1200, 760), title="Exercise")
  46. slider = plt.add_slider(update_plot, -10.0, 10.0, value=C_init, title="C value", c="green3")
  47. update_plot() # Initial plot
  48. plt.show(__doc__, mode="2d", zoom=1.35)