Han-Kwang Nienhuys - 11 months ago 28

Python Question

Consider the following Python script:

`import matplotlib.pyplot as plt`

import numpy as np

x, y = np.meshgrid(np.arange(10), np.arange(10))

z = x**2-y**2+718

fig, ax = plt.subplots(1)

ax.set_xlim(650,780)

im = ax.pcolormesh(x*130./9+650, y, z, vmin=650, vmax=780)

fig.colorbar(im)

plt.show(block=False)

raw_input("Press ENTER to quit.")

This produces a colormap plot with the x-axis from 650 to 780, with ticks at 660, 680, 700, and so on. The colorbar has the same range, but it has ticks at 660, 675, 690, 705, at integer multiples of 15.

Some experimentation shows that ticks can appear at multiples of 10, 15, 20, 25, 40, 50, and 80. This does not happen with the x axis, which is always in multiples of 10, 20, or 50 (add or remove zeros as applicable). Is it possible to make the colorbar behave the same way? I find it difficult to read values from the colorbar when the ticks have such an odd spacing, without multiples of 100 unless they happen to be divisible by 300.

I'm aware that I can control the ticks by supplying an array of tick values, but that requires that I know the data range beforehand. So that's not where I want to go.

Note: using Python 2.7.5, Matplotlib 1.3.1.

Answer

The way that mpl locates the ticks is through the use of a `Locator`

objects attached to the `Axes`

object (see ticker docs)

The default for most axes is to use `AutoLocator`

, but for whatever reason, the colorbar uses a `MaxNLocator`

. Via the `ticks`

kwarg `fig.colorbar`

you can pass in a `Locator`

instance, thus to get the same behavior as the x and y axis,

```
import matplotlib.ticker as mticker
cb = fig.colorbar(im, ticks=mticker.AutoLocator())
```

or to specify a specific step size

```
cb = fig.colorbar(im, ticks=mticker.MultipleLocator(25))
```

PR #6375 makes using `AutoLocator`

the default behavior