How to plot a 2D function in general form using Gadfly in Julia?

410 views Asked by At

From this question I learned how to plot functions in a "deterministic form" (like y = a0x + a1x^2 + a2x^3 ...). I am wondering how to plot a function in a general form (like ax + by + c = 0)?

For some simple function in a general form, we can transform it to a "deterministic form", then convert the math function into a Julia function (like ax + by + c = 0 to y = (ax + c)/(-b)). However, for some complex function, it is not easy to write a Julia function.

For example: enter image description here

Is there a way I can plot this function using Gadfly?

1

There are 1 answers

0
Jay Wang On BEST ANSWER

Mattriks suggests to use Geom.contour to plot functions in a general form in this issue.

I have tried it in my example, and it works pretty good.

For example, in the function on the question: enter image description here

Say the list of parameters is

para=[1.27274,0.625272,1.18109,-2.01996,-0.917423,-1.43166,0.124006,-0.365534,-0.357239,-0.175131,-1.45816,-0.0509896,-0.615555,-0.274707,-1.19282,-0.242188,-0.206006,-0.0447305,-0.277784,-0.295378,-0.456357,-1.0432,0.0277715,-0.292431,0.0155668,-0.327379,-0.143887,-0.924652]

In other words, a0 = 1.27274, a1 = 0.625272, etc.

Then we can use the following code to plot the graph.

function decision(x1::Float64, x2::Float64, a::Array{Float64})
    dot(a, [1, x1^1*x2^0, x1^0*x2^1, x1^2*x2^0, x1^1*x2^1, x1^0*x2^2, 
               x1^3*x2^0, x1^2*x2^1, x1^1*x2^2, x1^0*x2^3, x1^4*x2^0, x1^3*x2^1,
               x1^2*x2^2, x1^1*x2^3, x1^0*x2^4, x1^5*x2^0, x1^4*x2^1, x1^3*x2^2,
               x1^2*x2^3, x1^1*x2^4, x1^0*x2^5, x1^6*x2^0, x1^5*x2^1, x1^4*x2^2, 
               x1^3*x2^3, x1^2*x2^4, x1^1*x2^5, x1^0*x2^6])
end

plot(z = (x1,x2) -> decision(x1, x2, para), 
              x = linspace(-1.0, 1.5, 100),
              y = linspace(-1.0, 1.5, 100),
              Geom.contour(levels = [0.0]))

enter image description here

To make levels = [0.0] work, we need to explicitly provide arguments x, y, z.