Meaning of cmap in contourf

inquiries picture inquiries · Mar 9, 2016 · Viewed 11.7k times · Source

I have two questions regarding usage of the contourf plotting function. I have been searching for answers but haven't found them.

  1. In the contourf function, there is a variable named cmap. What is this used for and what is its meaning? And what is cmap=cm.jet mean?

  2. When one puts x,y,z into contourf and then creates a colorbar, how do we get the minimum and maximum values by which to set the colorbar limits? I am doing it manually now, but is there no way to get the min and max directly from a contourf handle?

Answer

Suever picture Suever · Mar 9, 2016

The cmap kwarg is the colormap that should be used to display the contour plot. If you do not specify one, the jet colormap (cm.jet) is used. You can change this to any other colormap that you want though (i.e. cm.gray). matplotlib has a large number of colormaps to choose from.

Here is a quick demo showing two contour plots with different colormaps selected.

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

data = np.random.rand(10,10)

plt.subplot(1,2,1)
con = plt.contourf(data, cmap=cm.jet)
plt.title('Jet')
plt.colorbar()

hax = plt.subplot(1,2,2)
con = plt.contourf(data, cmap=cm.gray)
plt.title('Gray')
plt.colorbar()

enter image description here

As far as getting the upper/lower bounds on the colorbar programmatically, you can do this by getting the clim value of the contourf plot object.

con = plt.contourf(data);
limits = con.get_clim()

   (0.00, 1.05)

This returns a tuple containing the (lower, upper) bounds of the colorbar.