Book Image

matplotlib Plotting Cookbook

By : Alexandre Devert
Book Image

matplotlib Plotting Cookbook

By: Alexandre Devert

Overview of this book

Table of Contents (15 chapters)
matplotlib Plotting Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Adding a colormap legend to a figure


A colormap is a key ingredient to produce both readable and visually pleasing figures. However, we are doing science here, and esthetic is just a side objective. When using colormaps, we would like to know which value corresponds to a given color. In this recipe, we will look at a simple way to add such information to a figure.

How to do it...

We will use the same example, the Mandelbrot set. We simply add a call to pyplot.colorbar():

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

def iter_count(C, max_iter): 
  X = C 
  for n in range(max_iter): 
    if abs(X) > 2.: 
      return n 
    X = X ** 2 + C 
  return max_iter 

N = 512 
max_iter = 64 
xmin, xmax, ymin, ymax = -2.2, .8, -1.5, 1.5 
X = np.linspace(xmin, xmax, N) 
Y = np.linspace(ymin, ymax, N) 
Z = np.empty((N, N)) 

for i, y in enumerate(Y): 
  for j, x in enumerate(X): 
    Z[i, j] = iter_count(complex(x, y), max_iter) 

plt.imshow(Z, 
            cmap...