Plotting a R→C function

Is there a better way to plot a function that maps from real to complex numbers?

f(x) = 2x+x^2*1im
plot(real∘f, imag∘f, 0, 2π, legend=false, xlabel="Re", ylabel="Im")

When I plot an Array{Complex{Float64},1} I get the real and imaginary axes for free.

plot(rand(Complex{Float64},10))
1 Like

Could you broadcast the range you want to plot into the function?

plot(f.(0:π/8:2π), legend=false)

plot() seems to call the method you want when given an array of complex values.

I would like to keep this:

plot([sin cos],0,2π)

and be able to use it like this with minimal overhead

f(x) = -2*x+x*im
g(x) = x-x*im/2
plot([f g],0,2π)

Now that I think of it it all boils down to the values returned by the function. Would type annotating it somehow help? But then there will always be problematic cases like this: plot([sin g],0,2π)?

I think the best way to handle this is with a plot recipe? I’ve actually never made one so the following code may not be “correct”, but it does produce the desired result.

using Plots

@recipe function f(f::AbstractArray{F}, xmin::Number, xmax::Number) where {F <: Function}
    x = range(xmin, stop=xmax, length=20)
    #A mapreduce() would probably be better...
    y = reshape([fi(xi) for fi in f for xi in x], length(x), length(f))
    return y
end

f1(x) = 2x+x^2*1im
f2(x) = x-x*im/2
f3(x) = sin(x+1im)

plot([f1, f2, f3],0,2π)