Skip to content
Home » matplotlib Part 28 – 3D Contour Plots

matplotlib Part 28 – 3D Contour Plots

Spread the love

3D Contour Plots

Today we’ll be plotting contours in 3D. To this end we need the contour method. This method works in a similar way as in 2D. You can specify the stride, as well as the projection direction. For the latter, you use the zdir argument, which by default is set to ‘z’, but you can set it to ‘x’ or ‘y’ as well. Have a look at this simple example:

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

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

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

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

fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

# Let's plot. Here we have 20 steps and the projection direction is 'z'.
ax.contour(X, Y, Z, 20, zdir='z', cmap=mpl.cm.Blues)
Out[1]:
<matplotlib.contour.QuadContourSet at 0x1ea0f788348>

Now let’s change the number of steps to 100:

In [2]:
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

# Let's plot. Here we have 100 steps and the projection direction is 'z'.
ax.contour(X, Y, Z, 100, zdir='z', cmap=mpl.cm.Blues)
Out[2]:
<matplotlib.contour.QuadContourSet at 0x1ea12119f48>

And now let’s change the projection direction to ‘x’:

In [3]:
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

# Let's plot. Here we have 20 steps and the projection direction is 'x'.
ax.contour(X, Y, Z, 20, zdir='x', cmap=mpl.cm.Blues)
Out[3]:
<matplotlib.contour.QuadContourSet at 0x1ea12e48348>

and now to ‘y’:

In [4]:
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

# Let's plot. Here we have 20 steps and the projection direction is 'y'.
ax.contour(X, Y, Z, 20, zdir='y', cmap=mpl.cm.Blues)
Out[4]:
<matplotlib.contour.QuadContourSet at 0x1ea12efd608>

If you want to fill the spaces between the lines, you should use the contourf method instead:

In [5]:
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
ax.contourf(X, Y, Z, 20, zdir='x', cmap=mpl.cm.Blues)
Out[5]:
<matplotlib.contour.QuadContourSet at 0x1ea12e04e48>

Spread the love

Leave a Reply