Matplotlib: How to set number of ticks on an axis?

C

Caleb Hattingh

Hi

I tried several Google searches to no avail. I read through pretty
much most of the online docs at the matplotlib sourceforge site, but
didn't find what I was looking for. I went through the axis.py and
ticker.py code today, trying to find out how to set the number of
points (ticks) on an axis in Matplotlib.

I know that something like

will make the x-axis have the values specified, but Matplotlib appears
to have a very nice way of setting axis ticks with human-friendly
values that round in just the right way for a given set of data. I
still want that functionality, but I want to set how many ticks are on
a given axis.

It seems that the locater() classes are where I should look, and there
seem to be some defaults in ticker.py:

class AutoLocator(MaxNLocator):
def __init__(self):
MaxNLocator.__init__(self, nbins=9, steps=[1, 2, 5, 10])

I don't understand what this means :)

I would prefer not to hack this directly in the matplotlib code. How
can I change the number of ticks on an axis programmatically without
messing with the other ticklabel functionality?

Caleb
 
J

John Hunter

Caleb> It seems that the locater() classes are where I should
Caleb> look, and there seem to be some defaults in ticker.py:

Caleb> class AutoLocator(MaxNLocator): def __init__(self):
Caleb> MaxNLocator.__init__(self, nbins=9, steps=[1, 2, 5, 10])

Caleb> I don't understand what this means :)

Caleb> I would prefer not to hack this directly in the matplotlib
Caleb> code. How can I change the number of ticks on an axis
Caleb> programmatically without messing with the other ticklabel
Caleb> functionality?

Yes, you will want to use a MaxNLocator. Note that the MaxNLocator
sets the maximum number of *intervals* so the max number of ticks will
be the max number of intervals plus one.

from matplotlib.ticker import MaxNLocator
from pylab import figure, show, nx

fig = figure()
ax = fig.add_subplot(111)
ax.plot(nx.mlab.rand(1000))
ax.xaxis.set_major_locator(MaxNLocator(4))
show()


JDH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top