Szymon Bęczkowski
Szymon Bęczkowski

Reputation: 370

Plotting with a custom scale [0 π/2 π 3π/2 2π] in Julia

I would like to plot various functions with a radian scale (typically just 0..2π) in Julia. Is there a nicer way to achieve a scale like this without manually defining ticks' positions and labels?

using Plots

f₀ = 50;
t = range(0,stop=1/f₀,length=1000)
θ = 2*pi*f₀*t
y = sin.(θ)

plot(θ, y, xticks = ([0:π/2:2*π;], ["0","\\pi/2","\\pi","3 \\pi/2","2\\pi"]))

plot with a custom scale: 0 π/2 π 3π/2 2π

Upvotes: 2

Views: 418

Answers (1)

Bill
Bill

Reputation: 6086

Similar to Jason's idea, create a function to make xtick strings from an xtick range:

using Plots

f₀ = 50;
t = range(0,stop=1/f₀,length=1000)
θ = 2*pi*f₀*t
y = sin.(θ)

isintegralmultipleof(f, x) = f != 0 && x / f ≈ round(x / f)

function pifrac(x)
    if isintegralmultipleof(pi/2, x)
        n = Int(round(2 * x / π))
        return iseven(n) ? "$(n ÷ 2) \\pi" : "$(n) \\pi / 2"
    end
    return string(x)
end

pirange = [0:π/2:3*π;]

plot(θ, y, xticks = (pirange, pifrac.(pirange)))

Upvotes: 1

Related Questions