I want to make a plot in pylab which displays feet on the y axis, and subdivides feet into inches rather than fractions of a foot. This is not an issue in the metric system because unit subdivisions align with the decimal system, but it does make plots difficult to read when using Imperial units.
Is this possible?
What I have now:
40 ft |
39.90 |
39.80 |
39.70 |
39.60 |
39.50 |------------>
What I want:
40 ft |
39 11in |
39 10in |
39 9in |
39 8in |
39 7in |
39 6in |------------>
You could use ticker.FuncFormatter to create a custom tick label:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = np.linspace(0, 1, 100)
y = (np.random.random(100) - 0.5).cumsum()
fig, ax = plt.subplots()
ax.plot(x, y)
def imperial(x, pos):
ft, inches = divmod(round(x*12), 12)
ft, inches = map(int, [ft, inches])
return ('{} ft'.format(ft) if not inches
else '{} {} in'.format(ft, inches) if ft
else '{} in'.format(inches))
ax.yaxis.set_major_formatter(ticker.FuncFormatter(imperial))
plt.show()

To also control the location of the ticks, you could use a ticker.MultipleLocator.
For example, to place a tick mark every 4 inches, add
loc = ticker.MultipleLocator(4./12)
ax.yaxis.set_major_locator(loc)
to the code above.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With