Setting an automatic tick interval

Question:

When I draw a plot with pyplot, it automatically generates nice widely space tick marks and labels. Is there a simple way to adjust the spacing between the automatically generated marks? For example, in a plot where default tick positions are [2,4,6], have ticks at positions [2,3,4,5,6].

I know I can set the mark positions and labels with xticks() and yticks(), but I need to know the range of values first, and with different data, I’d need to adjust them manually.

Asked By: drevicko

||

Answers:

There are a whole bunch of tick locators and formatters, depending on what you want to standardize. Here’s an example of linearly spacing ticks, set up for comparison with the default:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame((np.random.random((2,30)).T),columns=['A','B'])
fig, axs = plt.subplots(1,2)
axs[0].scatter(df.A, df.B)
axs[0].set_title('Default y-locator')
from matplotlib.ticker import LinearLocator
axs[1].get_yaxis().set_major_locator(LinearLocator(numticks=12))
axs[1].set_title('12 evenly spaced y-ticks')
axs[1].scatter(df.A, df.B)

enter image description here
See, generally, http://matplotlib.org/api/ticker_api.html?highlight=fixedlocator#module-matplotlib.ticker and the example gallery.

Answered By: cphlewis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.