3

I'm having troubble creating a filled contour plot that has both a logarithmic color scaling as well as having more colors than whatever is chosen by default. I'm basically trying to follow this example but while adding more colors, but whenever I add more colors, the numbers on the colorbar disappear (ticks are still there).

My basic code is

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

z = np.random.lognormal(mean=10, sigma=3, size=(10,10))

fig, ax = plt.subplots()
levels=np.logspace(np.log10(np.min(z)),np.log10(np.max(z)),100)
plot = ax.contourf(z, levels, norm=LogNorm())

cbar = fig.colorbar(plot)

plt.show()

I've also tried using

plot = ax.contourf(z, levels, locator=ticker.LogLocator())

but I get the same result. Tick marks are there but there aren't any numbers on the color bar: enter image description here

Also, following the Matplotlib documentation, it seems like

plot = ax.contourf(z, 100, norm=LogNorm())

should get me 101 logarithmically-spaced color levels but it just defaults to the normal number.

JeffP
  • 324
  • 2
  • 13
  • Did you count the levels? It seems like there are indeed a lot (can't count if it's 50, 100 or 150 though). What exactly makes you think this plot is wrong? Or how should it look instead? – ImportanceOfBeingErnest Mar 31 '18 at 00:31
  • @ImportanceOfBeingErnest, there should be numbers to the right of the tick marks on the color bar. If you remove the levels argument from the contourf function, you'll get the numbers. – JeffP Apr 01 '18 at 01:50

1 Answers1

1

Turns out you need to give the colorbar a locator in addition to giving one to the plotting function:

locator = ticker.LogLocator(base=10)
clb  = plt.colorbar(plot, format='%.e', ticks=locator)

And instead of using the norm parameter, I used the locator in the plotting function as well, although it doesn't seem to make a difference other than appearing more consistent.

plot = ax.contourf(z, levels, locator=locator)

enter image description here

As a side note, newer versions of matplotlib (2.1.1 at least) has introduced the LogFormatterSciNotation function that creates a formatter object that can be used for the format argument that creates labels using 10^x kind of notation. Unfortunately the main version I'm using is 1.5.1 so I need to use the format string above.

JeffP
  • 324
  • 2
  • 13