diff --git a/PlotsBase/src/recipes.jl b/PlotsBase/src/recipes.jl index 597977e0a..2c8c6367c 100644 --- a/PlotsBase/src/recipes.jl +++ b/PlotsBase/src/recipes.jl @@ -1297,6 +1297,58 @@ end end @deps quiver shape path +# Creating recipe vectorfieldplot() +@userplot VectorFieldPlot # Define new plot type called `VectorFieldPlot`` +@recipe function f(vfp::VectorFieldPlot) # Recipe function to customize `VectorFieldPlot` + + vecfunc = vfp.args[1] # Extracts the vector field function from the arguments + + # Default values + steps = get(plotattributes, :steps, 11) # Number of steps (default : 11) + vf_xlims = get(plotattributes, :vf_xlims, (-10, 10)) # Vector field x limits + vf_ylims = get(plotattributes, :vf_ylims, (-10, 10)) # Vector field y limits + plot_xlims = get(plotattributes, :xlims, (-10, 10)) # Plot x limits + plot_ylims = get(plotattributes, :ylims, (-10, 10)) # Plot y limits + + # Generate 2D grid for vector field + x = range(vf_xlims[1], vf_xlims[2], length=steps) # x Coordinates + y = range(vf_ylims[1], vf_ylims[2], length=steps) # y Coordinates + X = [xi for xi in x, _ in y] # Grid of x coordinates + Y = [yi for _ in x, yi in y] # Grid of y coordinates + + # Compute vector components + U = [vecfunc(xi, yi)[1] for xi in x, yi in y] # Compute the x components of the vector + V = [vecfunc(xi, yi)[2] for xi in x, yi in y] # Compute the y components of the vector + + # Scale vectors + max_magnitude = maximum(sqrt.(U.^2 .+ V.^2)) # Maximum magnitude of the vectors + scale_factor = 1.5 * min(step(x), step(y)) / max_magnitude # Scaling factor to adjust the vector length + + # Plot attributes + aspect_ratio --> :equal + xlabel --> "x" + ylabel --> "y" + title --> "Vector Field" + xlims --> plot_xlims + ylims --> plot_ylims + xticks --> range(plot_xlims[1], plot_xlims[2], length=11) + yticks --> range(plot_ylims[1], plot_ylims[2], length=11) + grid --> true + minorgrid --> true + gridlinewidth --> 0.5 + gridstyle --> :dot + gridalpha --> 0.7 + legend --> false + + # Create the quiver plot + @series begin + seriestype := :quiver # Setting series type to quiver for vector field plotting + quiver := (scale_factor .* U, scale_factor .* V) # Scaling factor for vector components + linewidth --> 1.0 + arrow := (:arrow, 0.1) # Arrow style and size + X, Y # Grid coordinates for the quiver plot + end +end # -------------------------------------------------------------------- # 1 argument # --------------------------------------------------------------------