Last active
February 25, 2019 16:22
-
-
Save toby-p/fd3da00f071ed467f1c7183ce7699598 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def magnitude(x): | |
"""Get the order 10 magnitude of a float.""" | |
return int(math.log10(x)) | |
def mpl_y_scale(datamin, datamax, desired_n_steps=5, minmax_buffer=True): | |
"""Determine nicely spaced, nearest-decimal-rounded y-ticks, and y-axis | |
limits (with optional buffer) which centrally locate a line plot in a | |
Matplotlib figure axis. | |
""" | |
diff = datamax - datamin | |
mag = magnitude(diff) | |
step = 10**mag | |
ymin = datamin - (datamin%step) | |
if minmax_buffer and math.isclose(ymin, datamin): | |
ymin-=step | |
ymax = datamax - (datamax%step) + step | |
if minmax_buffer and math.isclose(ymax, datamax): | |
ymax+=step | |
n_steps = int((ymax-ymin)/step)+1 | |
yticks = [ymin+(i*step) for i in range(n_steps)] | |
while len(yticks)> desired_n_steps: | |
yticks = [s for i, s in enumerate(yticks) if i%2==0] | |
new_diff = yticks[1]-yticks[0] | |
while yticks[-1]<ymax: | |
yticks.append(yticks[-1]+new_diff) | |
while yticks[0]>ymin: | |
yticks.append(yticks[0]-new_diff) | |
return ymin, ymax, yticks |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment