8

I'm having some trouble setting up a pcolormesh plot with a colorbar that includes logarithmically spaced minor tick marks on the colorbar.

The closest I've come is something like this:

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

xbins = np.linspace(0, 1, 50)
ybins = np.linspace(0, 1, 50)

data = np.random.random((49,49))

fig, ax = plt.subplots()

im = ax.pcolormesh(xbins, ybins, data, norm=matplotlib.colors.LogNorm())

cb = fig.colorbar(im)

cb.ax.minorticks_on()

plt.savefig('test.png')

The trouble with this solution is that the minor ticks are spaced evenly in log space:

enter image description here

I'd like to set up the plot so I have evenly spaced minor ticks in linear space, which should show up unevenly spaced on this plot.

I know that I can manually set the minor tick labels using a FixedFormatter, but I'd prefer not to do that if possible since I will be making a large number of plots automatically.

5
  • I would guess you can just use a MultipleLocator for the minor ticks...
    – tacaswell
    Aug 22, 2014 at 20:40
  • @tcaswell Why not the subs keyword of matplotlib.org/api/ticker_api.html#matplotlib.ticker.LogLocator ?
    – esmit
    Aug 22, 2014 at 21:32
  • @esmit I tried that, but it horribly breaks the colorbar. Adding the line cb.ax.set_yscale('log', xsubs=[2,3,4,5,6,7,8,9]) produces this plot: i.imgur.com/amCHR5j.png
    – ngoldbaum
    Aug 22, 2014 at 21:35
  • @tcaswell I tried adding cb.ax.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(base=0.1)), but that doesn't work either: i.imgur.com/wzlTIMx.png. It looks like the colorbar y axis is really linear and goes from 0 to 1. (I guess LogNorm() does that?)
    – ngoldbaum
    Aug 22, 2014 at 21:40
  • I might have time to look at this in detail this weekend.
    – tacaswell
    Aug 22, 2014 at 21:42

2 Answers 2

3

I think the best way to custom colorbars' ticks is to use the "ticks" argument of the fig.colorbar method and not trying to modify the attributes of the axe that contains the colorbar.

from matplotlib.ticker import LogLocator
"..."
cb = fig.colorbar(im, ticks = LogLocator(subs=range(10)))       

enter image description here

1
  • This sets all ticks as major ticks, which means 1) they are equally long, and 2) if you try to change the formatter (cbar.formatter) then that formatter will cause labels to be drawn for all ticks, not just the bases.
    – cmeeren
    Apr 10, 2015 at 18:16
1

Added for posterity:
From this answer: @JoeKington https://stackoverflow.com/a/20079644/230468:

minorticks = p.norm(np.arange(1, 10, 2))
cb.ax.xaxis.set_ticks(minorticks, minor=True)

This is annoying that you have to create the tick locations manually, but it seems to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.