Skip to content

Instantly share code, notes, and snippets.

@ntim
Last active February 21, 2016 13:43
Show Gist options
  • Select an option

  • Save ntim/32bd76336c4fbc9f2993 to your computer and use it in GitHub Desktop.

Select an option

Save ntim/32bd76336c4fbc9f2993 to your computer and use it in GitHub Desktop.
F-Number axes scale for matplotlib
import numpy as np
import matplotlib.scale as mscale
import matplotlib.transforms as mtransforms
from matplotlib.ticker import Formatter, FixedLocator
class FNumberScale(mscale.ScaleBase):
name = 'fnumber'
def __init__(self, axis, **kwargs):
mscale.ScaleBase.__init__(self)
self.thresh = None # thresh
def get_transform(self):
return self.FNumberTransform(self.thresh)
def set_default_locators_and_formatters(self, axis):
class FNumberFormatter(Formatter):
def __call__(self, x, pos=None):
return "%.1f" % x
# Set major tick at each f-stop
axis.set_major_locator(FixedLocator(np.sqrt(2**np.arange(-2, 16))))
# Set minor tick at each half f-stop
axis.set_minor_locator(FixedLocator(np.sqrt(2**np.arange(-0.5, 14.5))))
axis.set_major_formatter(FNumberFormatter())
class FNumberTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
# Inverse of sqrt(2**a)
return np.log(a**2) / np.log(2)
def inverted(self):
return FNumberScale.InvertedFNumberTransform(self.thresh)
class InvertedFNumberTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
return np.sqrt(2**a)
def inverted(self):
return FNumberScale.FNumberTransform(self.thresh)
mscale.register_scale(FNumberScale)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment