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

Hi John I posted the following item on comp.lang.python,

    > but actually you're exactly who I was looking for, and I
    > could your address off one of your responses to another's
    > question (I didn't know you read news). By the way,
    > Matplotlib is one of the best python addons I have ---no
    > more printing Excel graphs to postscript files :slight_smile:


    > 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 and code
    > today, trying to find out how to set the number of points
    > (ticks) on an axis in Matplotlib.

    > I know that something like
    >>>> xticks(arange(5))

    > 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

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

    > I don't understand what this means :slight_smile:

    > 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

    > You probably know exactly what I need to do?

Yes, you will want to use a MaxNLocator. Note that the MaxNLocator
sets the maximum number of *intervals* so the maxnumber of ticks will
be the max number of intervals plus one. You could probably adapt
this code to make an ExactNLocator. If you do, please send it our way.

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

  fig = figure()
  ax = fig.add_subplot(111)

Also, please post questions to the matplotlib-users mailing list
rather than to me directly, as there are plenty of experts there
(unlink on c.l.python) who can help you.

Glad you're enjoying matplotlib!