Skip to content

Instantly share code, notes, and snippets.

@szapp
Last active December 10, 2019 15:12
Show Gist options
  • Save szapp/16282f5f59d68a254332e229abdc2084 to your computer and use it in GitHub Desktop.
Save szapp/16282f5f59d68a254332e229abdc2084 to your computer and use it in GitHub Desktop.
Smarter bounds for matplotlib.spines.Spine
"""
Smarter bounds
This function emulates set_smart_bounds of matplotlib.spines.Spine,
but correctly sets the extent of the axes.
"""
def smarterbounds(ax, which='both'):
"""
Limit the extent of the axes to remain within the first and last ticks
"""
if which == 'both' or which == 'x':
xbound_low = ax.get_xticks()[ax.get_xticks() >= ax.get_xlim()[0]][0]
xbound_high = ax.get_xticks()[ax.get_xticks() <= ax.get_xlim()[1]][-1]
ax.spines['top'].set_bounds(xbound_low, xbound_high)
ax.spines['bottom'].set_bounds(xbound_low, xbound_high)
if which == 'both' or which == 'y':
ybound_low = ax.get_yticks()[ax.get_yticks() >= ax.get_ylim()[0]][0]
ybound_high = ax.get_yticks()[ax.get_yticks() <= ax.get_ylim()[1]][-1]
ax.spines['left'].set_bounds(ybound_low, ybound_high)
ax.spines['right'].set_bounds(ybound_low, ybound_high)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment