Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In matplotlib 2.0, how do I revert colorbar behaviour to that of matplotlib 1.5?

I just upgraded to matplotlib 2.0 and in general, I'm very happy with the new defaults. One thing which I'd like to revert to the 1.5 behaviour is that of plt.colorbar, specifically the yticks. In the old matplotlib, only major ticks were plotted on my colorbars; in the new matplotlib, minor and major ticks are drawn, which I do not want.

Below is shown a comparison of the 1.5 behaviour (left) and the 2.0 behaviour (right) using the same colormap and logarithmic ticks.

A comparison of colorbar yticks

What defaults do I need to set in matplotlibrc in order to revert to the 1.5 behaviour shown on the left? If there is no way to do this using matplotlibrc, what other avenues are available for altering this globally beyond downgrading to matplotlib 1.5?

I have tried simply setting cbar.ax.minorticks_off() after every instance of cbar = plt.colorbar(mesh), but that doesn't solve the issue.

like image 522
John Coxon Avatar asked Apr 04 '17 15:04

John Coxon


1 Answers

It should be sufficient to just set the colorbar locator to a LogLocator from the matplotlib.ticker module, and then call update_ticks() on the colorbar instance.

For example, consider this minimal example which produces the colorbar you are seeing with minor ticks:

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

fig, ax = plt.subplots(1)

# Some random data in your range 1e-26 to 1e-19
data = 10**(-26. + 7. * np.random.rand(10, 10))

p = ax.imshow(data, norm=colors.LogNorm(vmin=1e-26, vmax=1e-19))

cb = fig.colorbar(p, ax=ax)

plt.show()

enter image description here

If we now add the following two lines before calling plt.show(), we remove the minor ticks:

cb.locator = ticker.LogLocator()
cb.update_ticks()

enter image description here

Alternatively, to achieve the same thing, you can use the ticks kwarg when creating the colorbar, and set that to the LogLocator()

cb = fig.colorbar(p, ax=ax, ticks=ticker.LogLocator())
like image 123
tmdavison Avatar answered Oct 21 '22 09:10

tmdavison