Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Matplotlib: plotting feet and inches

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    |------------>
like image 469
user234461 Avatar asked Oct 27 '25 08:10

user234461


1 Answers

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()

enter image description here


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. enter image description here

like image 158
unutbu Avatar answered Oct 29 '25 23:10

unutbu