Order of arguments in plotting

This is an example from QuanEcon Section 31. Optimal Growth I.

The following code tries to plot the linear interpolation and the true value of a function f.

f(x) = 2 .* cos.(6x) .+ sin.(14x) .+ 2.5
c_grid = 0:.2:1
f_grid = range(0,  1, length = 150)

Af = LinearInterpolation(c_grid, f(c_grid))

plt = plot(xlim = (0,1), ylim = (0,6))
plot!(plt, f, f_grid, color = :blue, lw = 2, alpha = 0.8, label = "true function")
plot!(plt, f_grid, Af.(f_grid), color = :green, lw = 2, alpha = 0.8,
      label = "linear approximation")
plot!(plt, f, c_grid, seriestype = :sticks, linestyle = :dash, linewidth = 2, alpha = 0.5,
      label = "")
plot!(plt, legend = :top)

And the graph will be as follows

However, if I change from

plot!(plt, f_grid, Af.(f_grid), color = :green, lw = 2, alpha = 0.8,
      label = "linear approximation")

to

plot!(plt, Af.(f_grid), f_grid, color = :green, lw = 2, alpha = 0.8,
      label = "linear approximation")

It will give me a different graph.

But, I have found that the graph doesn’t change if I change the order of arguments of f and f_grid. i,e

plot!(plt, f, f_grid, color = :blue, lw = 2, alpha = 0.8, label = "true function")

will give us the same graph as

plot!(plt, f_grid, f,color = :blue, lw = 2, alpha = 0.8, label = "true function")

I would appreciate it if someone can help me with this issue. To be more specific, why change of order in some command will result in a different graph while change the order in some commands will lead to the same graph.

(don’t forget to mention any packages you use, I’m assuming you’re plotting with Plots.jl)

Normally, plots assumes that arguments are in order y, x, y or x, y, z, but it also uses dispatch. It has, for instance, been decided that if the first argument isa Function, the next is rather a domain than a y, because it seems unlikely you would want to plot a y vector vs an x function.

Essentially, the fact that transposing doesn’t matter in one of those cases is the exception.

1 Like

Currently plot(x, g) == plot(g, x) == plot(x, g.(x)), but it would make sense to have: plot(g⁻¹, y) to mean plot(g⁻¹.(y), y)

For example:

using Plots; gr(legend=false, lw=3)
g(x) = log(x)
g⁻¹(y) = exp(y)
x = 0.1:0.01:2
plot(x, g)
y = g.(x)
# plot!(g⁻¹, y)  # this could be interpreted instead as: plot!(g⁻¹.(y),y)
plot!(g⁻¹.(y), y, ls=:dash)
1 Like

I think that’s rare enough it makes sense to force you to be explicit. But it’s a somewhat agree for me.

It definitely won’t change though.