8

I am trying to make a contour plot with defined levels and log norm. Below is an example:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
delta = 0.025

x = y = np.arange(0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1* Z2)

fig=plt.figure()
ax1 = fig.add_subplot(111)
lvls = np.logspace(-4,0,20)
CF = ax1.contourf(X,Y,Z,
         norm = LogNorm(),
         levels = lvls
        )
CS = ax1.contour(X,Y,Z,
         norm = LogNorm(),
         colors = 'k',
         levels = lvls
        )
cbar = plt.colorbar(CF, ticks=lvls, format='%.4f')
plt.show()

enter image description here My questions is:
The levels should be written in the format: '1x10^-4', '1.6x10^-4', ... How do i do this, without specifying each level manually?

I am using python 2.7.3 with matplotlib 1.1.1 on Windows 7.

user2145054
  • 215
  • 2
  • 3
  • 8
  • Try looking [here](http://stackoverflow.com/questions/5748076/python-matplotlib-contour-plot-logarithmic-color-scale) or [here](http://matplotlib.1069221.n5.nabble.com/logarithmic-scale-of-colorbar-with-ticks-and-custom-labels-td21663.html). – wflynny Jul 30 '13 at 16:06
  • depending on how you want the levels to be labelled, check [this answer](http://stackoverflow.com/questions/16529038/matplotlib-tick-axis-notation-with-superscript/16530841#16530841) – Schorsch Jul 30 '13 at 19:35
  • Thanks for the answers. That would solve Question 1. Do you also have an idea for question 2? – user2145054 Aug 01 '13 at 15:03
  • You should ask one question per thread. Please ask accept the existing answer for you first question, edit this question to remove the second, and open a new question to ask it. – tacaswell Aug 09 '13 at 14:19

1 Answers1

8

From here I found an approach that seems to fit your question:

from matplotlib.ticker import LogFormatter
l_f = LogFormatter(10, labelOnlyBase=False)
cbar = plt.colorbar(CF, ticks=lvls, format=l_f)

which will give:

enter image description here

note that the spacing between the ticks are indeed in log scale...

Community
  • 1
  • 1
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234