Plot with x-axis in radians with ticks at multiples of pi

I have a plot where the x-axis is an angle in radians. Is there an easy way to make the ticks and the tick labels be multiples of pi?

For example, I would like to obtain a figure like this:

image

You may check this example from il bel paese.

A working example with Plots.jl:

using Plots, LaTeXStrings
pyplot(fmt=:svg)

function pitick(start, stop, denom; mode=:text)
    a = Int(cld(start, π/denom))
    b = Int(fld(stop, π/denom))
    tick = range(a*π/denom, b*π/denom; step=π/denom)
    ticklabel = piticklabel.((a:b) .// denom, Val(mode))
    tick, ticklabel
end

function piticklabel(x::Rational, ::Val{:text})
    iszero(x) && return "0"
    S = x < 0 ? "-" : ""
    n, d = abs(numerator(x)), denominator(x)
    N = n == 1 ? "" : repr(n)
    d == 1 && return S * N * "π"
    S * N * "π/" * repr(d)
end

function piticklabel(x::Rational, ::Val{:latex})
    iszero(x) && return L"0"
    S = x < 0 ? "-" : ""
    n, d = abs(numerator(x)), denominator(x)
    N = n == 1 ? "" : repr(n)
    d == 1 && return L"%$S%$N\pi"
    L"%$S\frac{%$N\pi}{%$d}"
end

a, b = -2π, 2π
plot(sin, a, b; xtick=pitick(a, b, 4), label="y = sin(x)", size=(720, 250))

plot(sin, a, b; xtick=pitick(a, b, 4; mode=:latex), label="y = sin(x)", size=(720, 250), tickfontsize=10)

Edit: LaTeX style tick labels

7 Likes

A solution with Makie:

using CairoMakie

format_π_fracs(xs; denom=round(Int, π/minimum(diff(xs)))) = map(xs) do x
    # This will error if x is not an expected fraction of π
    frac = Int(round(x/(π/denom), digits=1))//denom
    sign = x < 0 ? "-" : ""
    absnum = abs(frac.num) == 1 ? "" : string(abs(frac.num))
    frac.den == 1 && return frac.num == 0 ? L"0" : L"%$sign%$(absnum)\pi"
    return L"%$sign\frac{%$(absnum)\pi}{%$(frac.den)}"
end

lines(-2π..2π, sin, figure=(; resolution=(600, 200)),
      axis=(xticks=-2π:π/2:2π, xtickformat=format_π_fracs))

image

5 Likes