plotgraphjuliagadfly

How to plot a linear function using Gadfly.jl in Julia?


I am wondering how to graph a linear function (say y = 3x + 2) using Julia package Gadfly. One way I come up with is to plot two points on that line, and add Geom.line.

using Gadfly

function f(x)
    3 * x + 2
end

domains = [1, 100]
values = [f(i) for i in domains]
p = plot(x = domains, y = values, Geom.line)
img = SVG("test.svg", 6inch, 4inch)
draw(img, p)

enter image description here

Are there any better way to plot lines? I have found the Functions and Expressions section on the Gadfly document. I am not sure how to use it with linear functions?


Solution

  • You may plot the function directly, passing it as an argument to the plot command (as you pointed at documentation), followed by the start and end points at X axis (domain):

    julia> using Gadfly
    
    julia> f(x) = 3x + 2
    f (generic function with 1 method)
    
    julia> plot(f, 1.0, 100.0)
    

    enter image description here

    Even more complex expressions can be plotted the same way:

    julia> f3(x) = (x >= 2.0) ? -2.0x+1.0 : 2.0x+1.0
    f3 (generic function with 1 method)
    
    julia> plot(f3, -5, 10)
    

    enter image description here

    If you want to plot two (or more) functions at same graph, you may pass an array of functions as the first argument:

    julia> plot([f, f3], -5, 10)
    

    enter image description here

    tested with: Julia Version 0.5.0