Skip to content
Home » matplotlib Part 23 – Contour Plots

matplotlib Part 23 – Contour Plots

Spread the love

Contour Plots

In the previous article we were talking about color maps. Today we’ll be talking about contour maps, which are pretty similar. Instead of the pcolor method, you use the contour method. So, let’s recreate the example from the previous article first:

In [1]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# Let's create the x and y values.
x = y = np.linspace(0, 10, 100)

# Let's format the data.
X, Y = np.meshgrid(x, y)

# Let's define the values of Z.
Z = np.sin(X) ** 5 + np.cos(Y) * np.cos(X)

# Let's create the color map
fig, ax = plt.subplots()
ax.pcolor(X, Y, Z)
Out[1]:
<matplotlib.collections.PolyCollection at 0x1cc788692c8>

And now let’s change it to a contour plot:

In [2]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z)
Out[2]:
<matplotlib.contour.QuadContourSet at 0x1cc76ddfb08>

Just like with the color map, you can set the cmap argument to one of the predefined values:

In [3]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, cmap=mpl.cm.bwr)
Out[3]:
<matplotlib.contour.QuadContourSet at 0x1cc795f5c08>
In [4]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, cmap=mpl.cm.Dark2)
Out[4]:
<matplotlib.contour.QuadContourSet at 0x1cc79695948>
In [5]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, cmap=mpl.cm.hot)
Out[5]:
<matplotlib.contour.QuadContourSet at 0x1cc79714388>

You can also set one color by passing a single value to the colors argument. Then positive values are represented by solid lines and negative ones by dashed lines:

In [6]:
# set color to black
fig, ax = plt.subplots()
ax.contour(X, Y, Z, colors='k')
Out[6]:
<matplotlib.contour.QuadContourSet at 0x1cc7978e108>

You can also specify more than one color:

In [7]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, colors=['k', 'r'])
Out[7]:
<matplotlib.contour.QuadContourSet at 0x1cc79809708>

We can also create a contour plot with the spaces between the lines filled. To this end we use the contourf method:

In [8]:
fig, ax = plt.subplots()
ax.contourf(X, Y, Z)
Out[8]:
<matplotlib.contour.QuadContourSet at 0x1cc79889788>

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply