Skip to content

Instantly share code, notes, and snippets.

@vleugelcomplement
Last active September 21, 2023 12:53
Show Gist options
  • Save vleugelcomplement/aa69e43c3d8b804864ede4a8c056e9cd to your computer and use it in GitHub Desktop.
Save vleugelcomplement/aa69e43c3d8b804864ede4a8c056e9cd to your computer and use it in GitHub Desktop.
matplotlib ticks at multiples of pi
"""
An example of an attempt to get non-standard ticks in matplotlib plot.
Here, we use π/3 as unit length.
"""
import numpy as np
from fractions import Fraction as frac
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MultipleLocator
# to set nicer colors
import seaborn as sb
sb.set_style('whitegrid', {'grid.linestyle': '--'})
sb.set_palette("dark")
# better resolution & TeX support
dpi,fontsize = 120,8
plt.rc('text', usetex=True)
plt.rc('savefig', dpi=dpi)
plt.rc('figure', dpi=dpi)
plt.rc('font', size=fontsize)
def pi_axis_formatter(val, pos, denomlim=10, pi=r'\pi'):
"""
format label properly
for example: 0.6666 pi --> 2π/3
: 0 pi --> 0
: 0.50 pi --> π/2
"""
minus = "-" if val < 0 else ""
val = abs(val)
ratio = frac(val/np.pi).limit_denominator(denomlim)
n, d = ratio.numerator, ratio.denominator
fmt2 = "%s" % d
if n == 0:
fmt1 = "0"
elif n == 1:
fmt1 = pi
else:
fmt1 = r"%s%s" % (n,pi)
fmtstring = "$" + minus + (fmt1 if d == 1 else r"{%s}/{%s}" % (fmt1, fmt2)) + "$"
return fmtstring
plt.figure(figsize=(10,3))
ax = plt.gca()
ax.set_aspect('equal')
# an example of plot that benefits from non-standard ticks
xx = np.linspace(-2*np.pi, 2*np.pi,100)
ax.plot(xx, np.sin(xx))
ticklen = np.pi/3
# setting ticks labels
ax.xaxis.set_major_formatter(FuncFormatter(pi_axis_formatter))
# setting ticks at proper numbers
ax.xaxis.set_major_locator(MultipleLocator(base=ticklen))
plt.grid(True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment