3D Plot in Python: A Quick Guide

Ask Python

We are going to learn several methods for plotting 3D plots in Python with their appropriate uses. We are going to work on our Google Colab notebook. Let’s get into it.

Required Methods for Plotting

Before getting started with our examples, Let’s understand the methods as well. We are going to use them further.

numpy.linespace()

This method is used to plot values in our required axis. The syntax for numpy.linespace() is as follows.

numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None)

The Parameters for this method are :

  • start: Beginning of our axes coordinate.
  • stop: Ending of our axes coordinate.
  • num: No. of dot samples to be plotted
  • restep: If True, return (samples, step). By default restep = False. (Optional)
  • dtype: type of output array. (Optional)

We can better understand by following an example as follow.

import numpy as np
import pylab as p
 
# taking Start = 0, End = 2 and num=15 as parameters 
x1 = np.linspace(0, 2, 15, endpoint = True)
y1 = np.zeros(15) 
 
#taking x axis from -0.2 to 2.1 in our graph
p.xlim(-0.2, 2.1)

#plotting graph
p.plot(x1, y1, "*")

The code snippet will give the result as follows.

numpy.linespace() method output
numpy.linespace() method output

numpy.mgrid

An instance of NumPy library that returns a multi-dimensional mesh grid. A mesh grid is a 2d array with similar values. This method calls the mesh grid method to initialize dense multidimensional arrays. The dimensions and number of the output arrays are equal to the number of indexing dimensions.

The syntax for numpy.mgrid is as follows.

numpy.mgrid = <numpy.lib.index_tricks.nd_grid object>

We can better understand the following examples in our code snippet.

>>> import numpy as np
>>> new = np.mgrid[0:6, 0:4]
>>> print(new)
[[[0 0 0 0]
  [1 1 1 1]
  [2 2 2 2]
  [3 3 3 3]
  [4 4 4 4]
  [5 5 5 5]]

 [[0 1 2 3]
  [0 1 2 3]
  [0 1 2 3]
  [0 1 2 3]
  [0 1 2 3]
  [0 1 2 3]]]
>>> new2 = np.mgrid[0:3, 0:5]
>>> print(new2)
[[[0 0 0 0 0]
  [1 1 1 1 1]
  [2 2 2 2 2]]

 [[0 1 2 3 4]
  [0 1 2 3 4]
  [0 1 2 3 4]]]

Let’s start plotting our 3D models using different methods.

Plotting a 3D model using .plot3D() method

Plotting our 1st 3D model in Python, we are going to create a Solenoid using python in a 3D graph. Let’s have a look at our code snippet below.

#importing required modules for 3D plotting
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

#creating our 3D space using projection=3D parameter
ax = plt.axes(projection='3d')

#using linespace() method to assign plotting range of z-axis
zline = np.linspace(10, 200, 1000)
#taking x-intercept and y-intercept values as sin(zvalue) and cos(zvalue) respectively for different zvalue as radian.  
xline = np.sin(zline)
yline = np.cos(zline)

#using plot3D() method by passing 3 axes values and plotting colour as "green" 
ax.plot3D(xline, yline, zline, 'green')

By following the above code snippet, we can get our output as follows.

Example 1 Output
Example 1 Output

You can try the above code snippet by changing the parameter values. You can get various other results and could better understand as well. Let’s look at another example of a 3D model.

Plotting a 3D model using .scatter3D() method

Plotting our 2nd 3D model. We are going to create a scattered dotted Solenoid using python in a 3D graph. Let’s have a look at our code snippet below.

#importing modules and creating a 3D as previous example 
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
ax = plt.axes(projection='3d')

a = 500
# Data for three-dimensional scattered points
zdata = 50 * np.random.random(a)
xdata = np.sin(zdata) + 0.0 * np.random.random(a)
ydata = np.cos(zdata) + 0.0 * np.random.random(a)

#using the scatter3D() method by passing 3 co-ordinates 
ax.scatter3D(xdata, ydata, zdata);

By following the above code snippet, we can get our output as follows.

Example 2 Output
Example 2 Output

By changing values on our same code snippet in parameters, We can expect different plots as follows.

# Data for three-dimensional scattered points
a = 400
zdata = 20 * np.random.random(a)
xdata = np.sin(zdata) + 0.3 * np.random.random(a)
ydata = np.cos(zdata) + 0.1 * np.random.random(a)
ax.scatter3D(xdata, ydata, zdata);
Example 2 Output After Changing Parameter Values
Example 2 Output After Changing Parameter Values

Plotting a surface from a list of tuples

In this method, we are going to plot the surface for some tuples (Consider tuples as coordinates).

import numpy as np
from matplotlib import pyplot as plt

ax = plt.axes(projection='3d')

# List of tuples
tuple_list = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]

# Data points from the list of tuples
x, y, z = zip(tuple_list)
x, y = np.meshgrid(x, y)
Z = x ** 2 + y ** 2

# Surface plotting using .plot_surface() method
ax.plot_surface(x, y, Z)

plt.show()

By following the above code snippet, we can get our output as follows.

Surface By Tuples
Surface By Tuples

Plotting a 3D model using .plot_surface() method

In this method, We are going to plot points on the surface of a sphere in Python using plot_surface().

import matplotlib.pyplot as plt
import numpy as np

ax = plt.axes(projection='3d')

getting the values for spherical points 
u, v = np.mgrid[0:2 * np.pi:50j, 0:np.pi:50j]
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)

#Plotting the surface using plot_surface() method
ax.plot_surface(x, y, z)
plt.show()

By following the above code snippet, We will get the output as below.

Plot Surface Method
Plot Surface Method

Summary

In this article, we covered how to plot 3D models using Python. We plotted a solenoid, a sphere, and a normal plane. You can try the same code snippets with different values as parameters to get different outputs. We can learn more as well. Hope You must have enjoyed it.