Skip to content

Instantly share code, notes, and snippets.

@lebedov
Created April 4, 2017 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lebedov/1e73edb01af4e44ceb3b37b9e068ef86 to your computer and use it in GitHub Desktop.
Save lebedov/1e73edb01af4e44ceb3b37b9e068ef86 to your computer and use it in GitHub Desktop.
Adjust evenly spaced ticks on current matplotlib axis.
#!/usr/bin/env python
"""
Adjust evenly spaced ticks on current matplotlib axis.
"""
import matplotlib.pyplot as plt
import numpy as np
def tick_space(space, which='major', axis='both'):
"""
Adjust evenly spaced ticks on current axis.
Parameters
----------
space : float
Space between each tick.
which : str
Can be 'major', 'minor', or 'both'.
axis : str
Can be 'x', 'y', or 'both'
Notes
-----
Grid visibility and other properties should be set via
`matplotlib.pyplot.grid`.
"""
ax = plt.gca()
if axis in ['x', 'both']:
ticks = ax.axes.get_xticks()
lim = ax.axes.get_xlim()
a = min(min(ticks), min(lim))
b = max(max(ticks), max(lim))
if which in ['major', 'both']:
new_ticks = np.arange(a, b, space)
ax.set_xticks(new_ticks)
ax.set_xlim(lim)
if which in ['minor', 'both']:
new_ticks = np.arange(a, b, space)
ax.set_xticks(new_ticks, minor=True)
ax.set_xlim(lim)
if axis in ['y', 'both']:
ticks = ax.axes.get_yticks()
lim = ax.axes.get_ylim()
a = min(min(ticks), min(lim))
b = max(max(ticks), max(lim))
if which in ['major', 'both']:
new_ticks = np.arange(a, b, space)
ax.set_yticks(new_ticks)
ax.set_ylim(lim)
if which in ['minor', 'both']:
new_ticks = np.arange(a, b, space)
ax.set_yticks(new_ticks, minor=True)
ax.set_ylim(lim)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment