Color the lines in a contour plot of `z` by the values a different matrix `w`

Let’s say I have the following MWE

using Plots

x = y = range(0, stop=π, length=100)

z = cos.(x) .+ sin.(y')
w = cos.(x).^2 .- sin.(y').^2

contour(x,y,z, levels=1)

I would like the lines from the contour plot of z to be coloured using the values of w. Is this possible in some way?

One approach I tried is extracting the contours manually using Contour.jl but I got stuck on how to extract the contour mask to apply to w so I can use the line_z kwarg. (see Contour.jl: extract the indices of the contour)

Thoughts? I would love to do this using Plots.jl since that’s what my entire code base is based on but I am open to solutions since I have been stuck on this for a while now.

The following works for w = w(x,y), but if you have only a numerical matrix w then I think you could define an interpolator function of (x,y) to be called:

using Contour, Plots; gr(dpi=600)

x = y = range(0, π, 100)
z = @. cos(x) + sin(y')
w(x,y) = @. cos(x)^2 - sin(y')^2

plot()
for cl in levels(contours(x,y,z))
    for line in lines(cl)
        xs, ys = coordinates(line)   # coordinates of each contour line
        plot!(xs, ys, st=:path, markershape=:none, line_z = w(xs,ys))    # use plotting package you prefer
    end
end
Plots.current()

1 Like