How to plot quiver plot over heatmap

I am trying to plot a quiver plot (a vector field) over a heatmap. My only reference after one day of research is this old notebook: https://github.com/JuliaPlots/ExamplePlots.jl/blob/master/notebooks/quiver.ipynb

My function is

initial_c(x, y, z) = (exp(-x^2 - y^2))

Is there a way to do this and even print out the values of every vector for the respective grid point?

Plots.jl examples

Example 1:

using ForwardDiff
using Plots

f(x, y) = exp(-(x^2 + y^2))
u(x, y) = ForwardDiff.derivative(Base.Fix2(f, y), x) # = f_x(x, y)
v(x, y) = ForwardDiff.derivative(Base.Fix1(f, x), y) # = f_y(x, y)

xlim = (-1.7, 1.7)
ylim = (-1.7, 1.7)
xs = range(xlim...; length=200)
ys = range(ylim...; length=200)

c = 0.5
x = range(-1.5, 1.5; length=11)
y = range(-1.5, 1.5; length=11)
X, Y = reim(complex.(x', y)) # meshgrid
U, V = c*u.(x', y), c*v.(x', y)

heatmap(xs, ys, f)
quiver!(vec(X-U/2), vec(Y-V/2); quiver=(vec(U), vec(V)), color=:cyan)
plot!(; xlim, ylim, size=(450, 400))

Example2:

using ForwardDiff
using Plots

f(x, y) = y * exp(-(x^2 + y^2))
u(x, y) = -ForwardDiff.derivative(Base.Fix2(f, y), x) # = f_x(x, y)
v(x, y) = -ForwardDiff.derivative(Base.Fix1(f, x), y) # = f_y(x, y)

xlim = (-2.2, 2.2)
ylim = (-2.2, 2.2)
xs = range(xlim...; length=200)
ys = range(ylim...; length=200)

c = 0.5
x = range(-2.0, 2.0; length=13)
y = range(-2.0, 2.0; length=13)
X, Y = reim(complex.(x', y)) # meshgrid
U, V = c*u.(x', y), c*v.(x', y)

heatmap(xs, ys, f)
quiver!(vec(X-U/2), vec(Y-V/2); quiver=(vec(U), vec(V)), color=:cyan)
plot!(; xlim, ylim, size=(450, 400))

4 Likes

Can I ask why the second example has

u(x, y) = -ForwardDiff.derivative(Base.Fix2(f, y), x) # = f_x(x, y)
v(x, y) = -ForwardDiff.derivative(Base.Fix1(f, x), y) # = f_y(x, y)

why you add the minus?

For the first one the quiver represents the gradient vector field, grad(f), while in the second one minus gradient. Most likely @genkuroki made this choice for variation or to illustrate that grad(f), respectively -grad(f) is the direction of steepest ascent/descent.