Skip to content

Instantly share code, notes, and snippets.

@NoFishLikeIan
Last active December 11, 2023 10:55
Show Gist options
  • Save NoFishLikeIan/a2b6e5bf5da129873c60d90eee13a4ec to your computer and use it in GitHub Desktop.
Save NoFishLikeIan/a2b6e5bf5da129873c60d90eee13a4ec to your computer and use it in GitHub Desktop.
Small routine to plot vector fields
begin
function plotvectorfield(xs, ys, g::Function; plotkwargs...)
fig = plot()
plotvectorfield!(fig, xs, ys, g; plotkwargs...)
return fig
end
function plotvectorfield!(figure, xs, ys, g::Function; rescale = 1, plotkwargs...)
xlims = extrema(xs)
ylims = extrema(ys)
N, M = length(xs), length(ys)
xm = repeat(xs, outer=M)
ym = repeat(ys, inner=N)
field = g.(xm, ym)
scale = rescale * (xlims[2] - xlims[1]) / min(N, M)
u = @. scale * first(field)
v = @. scale * last(field)
steadystates = @. (u ≈ 0) * (v ≈ 0)
u[steadystates] .= NaN
v[steadystates] .= NaN
z = (x -> √(x'x)).(field)
quiver!(
figure, xm, ym;
quiver = (u, v), line_z=repeat(z, inner=4),
aspect_ratio = 1, xlims = xlims, ylims = ylims,
c = :batlow, colorbar = false,
plotkwargs...
)
end
end
@NoFishLikeIan
Copy link
Author

NoFishLikeIan commented Oct 13, 2021

Use as

narrows = 21
xs = ys = range(0, 1; length = narrows)
plotvectorfield(
  xs, ys, f; 
  xlabel = "\$x_1\$", ylabel = "\$x_2\$",
  title = "Vector field of \$f(x)\$"
)

vecfield

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment