3D Contour Plotting in Python using Matplotlib

Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let’s look at a 3d contour diagram of a 3d cosine function. The code is attached for reference.

Function Arguments Description
meshgrid Function of numpy used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing
plt.axes() To create object of the axis
ax.contour3D To form the contour
ax.set_xlabel To label the X-axis
ax.set_title To give a title to the plot

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import math
  
x = [i for i in range(0, 200, 100)]
y = [i for i in range(0, 200, 100)]
  
X, Y = np.meshgrid(x, y)
Z = []
for i in x:
    t = []
    for j in y:
        t.append(math.cos(math.sqrt(i*2+j*2)))
    Z.append(t)
  
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap=cm.cool)
ax.set_xlabel('a')
ax.set_ylabel('b')
ax.set_zlabel('c')
ax.set_title('3D contour for cosine')
plt.show()

chevron_right


Output:
3D Contour Plotting

Example 2: Let’s look at another 3d diagram for better understanding of the concept. This time, of a 3d tan function.

filter_none

edit
close

play_arrow

link
brightness_4
code

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import math
  
x = [i for i in range(0, 200, 100)]
y = [i for i in range(0, 200, 100)]
  
X, Y = np.meshgrid(x, y)
Z = []
for i in x:
    t = []
    for j in y:
        t.append(math.tan(math.sqrt(i*2+j*2)))
    Z.append(t)
  
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap=cm.cool)
ax.set_xlabel('a')
ax.set_ylabel('b')
ax.set_zlabel('c')
ax.set_title('3D contour for tan')
plt.show()

chevron_right


Output:
3D Contour Plotting

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.