Plotting 3D-graphs in Python using matplotlib

Today we’ll learn about plotting 3D-graphs in Python using matplotlib. Matplotlib is an amazing module which not only helps us visualize data in 2 dimensions but also in 3 dimensions. 3D graphs represent 2D inputs and 1D output. The submodule we’ll be using for plotting 3D-graphs in python is mplot3d which is already installed when you install matplotlib. So, you need to make sure you have installed matplotlib to implement this tutorial.

So, Let’s get started!


In this tutorial, we will be using the 3D plots in matplotlib. There are also other options like pandas3D. Feel free to play around with that too.

The submodule of matplotlib called mpl_toolkits is used to plot our 3D graphs. Check out its documentation here. We will also import matplotlib.pyplot itself too.

from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
%matplotlib inline

Making our dataset for 3d graph plotting

Now we need to get our x, y, and z values so that we can plot them. You can also make use of a csv or excel dataset to make it easier to visualize. Here, we’ll create three numpy arrays representing x, y, and z values.

For this, first import numpy and randint() function to create random datavalues:

import numpy as np
from random import randint

We then define our numpy arrays by using the randint() function and list comprehension.

x=np.array([randint(0,100) for x in range(10)])
y=np.array([randint(0,100) for x in range(10)])
z=np.array([randint(0,100) for x in range(10)])

Now, let’s see what our values are :



array([15, 50, 70,  7, 62,  3, 47, 33, 22, 41])
array([62, 82, 94, 41,  1, 48, 75, 78, 95, 92])
array([34, 13, 73, 75, 33, 54, 80, 16, 70, 80])

Plotting our 3d graph in Python with matplotlib

Let’s first start by defining our figure


Now, to create a blank 3D axes, you just need to add “projection=’3d’ ” to plt.axes()

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

The output will look something like this:

How to plot 3D graphs in Python using Matplotlib

Now we add label names to each axis. To keep it simple, we’re just naming them ‘x’, ‘y’and ‘z’ respectively. Also, note that the function is ‘set_xlabel’ unlike in 2D plot where it isĀ  just ‘xlabel ‘


Finally, we get to the part where we plot the graph. The function used is plot3D().



How to plot 3D graphs in Python using Matplotlib

We plotted the line graph here. There are a number of plotting techniques we can use like contour3D, scatter3D, plot_wireframe, and plot_surface, etc.


Also read:

KNN Classification using Scikit-Learn in Python

Mouse Automation in Python using PyAutoGUI

One response to “Plotting 3D-graphs in Python using matplotlib”

  1. Konstantinos Anastasiadis says:

    How do I plot in 3D
    a polyhedron using 3d vectors as vertices and arrays of vectors as faces

Leave a Reply

Your email address will not be published. Required fields are marked *