pythonmatplotlib

How to project a contour map on the xy plane using matplotlib?


How can I plot a contour map on the xy plane rather than on the 3d surface of the function?
I wanted to plot the contour where z = 0.
However, my currently output is producing this:

enter image description here


The following code is my implementation:

import numpy as np
import matplotlib.pyplot as plt

def f(x,y):
    return x**2 + y**2

x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
X,Y = np.meshgrid(x,y) # array of values containing all value pairs (xi, yi)
Z = f(X,Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, cmap="autumn_r", rstride=1, cstride=1)
ax.contour(X, Y, Z, 10, cmap="autumn_r", linestyles="solid")
plt.show()

Solution

  • If you want the contour to be on one of the planes then set the offset. offset=0 puts the contour on the Z=0 plane (since the default zdir is z).

    fig, ax = plt.subplots(subplot_kw={"projection":"3d"})
    ax.plot_surface(X, Y, Z, cmap="autumn_r", rstride=1, cstride=1)
    ax.contour(X, Y, Z, 10, offset=0, cmap="autumn_r", linestyles="solid")
    plt.show()
    

    See the Matplotlib demo here: https://matplotlib.org/stable/gallery/mplot3d/contour3d_3.html#sphx-glr-gallery-mplot3d-contour3d-3-py

    You may also wish to change contour to contourf.