Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?
This is my current output:
enter image description here

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading