# Introduction to 3D Plotting with Matplotlib

In this article, we will be learning about 3D plotting with **Matplotlib**. There are various ways through which we can create a 3D plot using matplotlib such as creating an empty canvas and adding axes to it where you define the projection as a 3D projection, **Matplotlib.pyplot.gca()**,** **etc.

**Creating an Empty 3D Plot: **

In the below code, we will be creating an empty canvas at first. After that, we will be defining the axes of our 3D plot where we define that the projection of the plot will be in “**3D**” format. This helps us to create the 3D empty axes figure in the canvas. After this, if we show the plot using **plt.show()**, then it would look like the one shown in the output.

**Example: **Creating an empty 3D figure using Matplotlib

## Python3

`# importing numpy package from` `# python library` `import` `numpy as np` `# importing matplotlib.pyplot package from` `# python` `import` `matplotlib.pyplot as plt` `# Creating an empty figure` `# or plot` `fig ` `=` `plt.figure()` `# Defining the axes as a` `# 3D axes so that we can plot 3D` `# data into it.` `ax ` `=` `plt.axes(projection` `=` `"3d"` `)` `# Showing the above plot` `plt.show()` |

**Output:**

Now, we have a basic idea about how to create a 3D plot on an empty canvas. Let us move to some 3D plotting examples.

**Examples **of** 3D plotting:**

**Example 1:**

In the below example, we will be taking a simple curve in our 3D plot. Along with that, we will be plotting a range of points that have X-coordinate, Y-coordinate as well as Z-coordinate.

## Python3

`# importing numpy package` `import` `numpy as np` `# importing matplotlib package` `import` `matplotlib.pyplot as plt` `# importing mplot3d from` `# mpl_toolkits` `from` `mpl_toolkits ` `import` `mplot3d` `# creating an empty canvas` `fig ` `=` `plt.figure()` `# defining the axes with the projection` `# as 3D so as to plot 3D graphs` `ax ` `=` `plt.axes(projection` `=` `"3d"` `)` `# creating a wide range of points x,y,z` `x` `=` `[` `0` `,` `1` `,` `2` `,` `3` `,` `4` `,` `5` `,` `6` `]` `y` `=` `[` `0` `,` `1` `,` `4` `,` `9` `,` `16` `,` `25` `,` `36` `]` `z` `=` `[` `0` `,` `1` `,` `4` `,` `9` `,` `16` `,` `25` `,` `36` `]` `# plotting a 3D line graph with X-coordinate,` `# Y-coordinate and Z-coordinate respectively` `ax.plot3D(x, y, z, ` `'red'` `)` `# plotting a scatter plot with X-coordinate,` `# Y-coordinate and Z-coordinate respectively` `# and defining the points color as cividis` `# and defining c as z which basically is a` `# definition of 2D array in which rows are RGB` `#or RGBA` `ax.scatter3D(x, y, z, c` `=` `z, cmap` `=` `'cividis'` `);` `# Showing the above plot` `plt.show()` |

**Output:**

**Explanation:**

- In the above example, first, we are importing packages from the python library in order to have a 3D plot in our empty canvas. So, for that, we are importing
**numpy**,**matplotlib.pyplot**, and**mpl_toolkits**. - After importing all the necessary packages, we are creating an empty figure using
**plt.figure()**. - After that, we are defining the axis of the plot where we are specifying that the plot will be of 3D projection.
- After that, we are taking 3 arrays with a wide range of arbitrary points which will act as X, Y, and Z coordinates for plotting the graph respectively. Now after initializing the points, we are plotting a 3D plot using ax.plot3D() where we are using x,y,z as the X, Y, and Z coordinates respectively and the color of the line will be red.
- All these things are sent as parameters inside the bracket.
- After that, we are also plotting a scatter plot with the same set of values and as we progress with each point, the color of the points will be based on the values that the coordinates contain.
- After this, we are showing the above plot.

**Example 2:**

In this example, we will be learning about how to do 3D plotting using **figure.gca(). **Here we will be creating a sine curve and a cosine curve with the values of x and y ranging from -5 to 5 with a gap of 1. Let us look at the code to understand the implementation.

## Python3

`# importing matplotlib.pyplot from` `# python` `import` `matplotlib.pyplot as plt` `# importing numpy package from` `# python` `import` `numpy as np` `# creating a range of values for` `# x,y,x1,y1 from -5 to 5 with` `# a space of 1 between the elements` `x ` `=` `np.arange(` `-` `5` `,` `5` `,` `1` `)` `y ` `=` `np.arange(` `-` `5` `,` `5` `,` `1` `)` `# creating a range of values for` `# x,y,x1,y1 from -5 to 5 with` `# a space of 0.6 between the elements` `x1` `=` `np.arange(` `-` `5` `,` `5` `,` `0.6` `)` `y1` `=` `np.arange(` `-` `5` `,` `5` `,` `0.6` `)` `# Creating a mesh grid with x ,y and x1,` `# y1 which creates an n-dimensional` `# array` `x, y ` `=` `np.meshgrid(x, y)` `x1,y1` `=` `np.meshgrid(x1,y1)` `# Creating a sine function with the` `# range of values from the meshgrid` `z ` `=` `np.sin(x ` `*` `np.pi` `/` `2` `)` `# Creating a cosine function with the` `# range of values from the meshgrid` `z1` `=` `np.cos(x1` `*` `np.pi` `/` `2` `)` `# Creating an empty figure for` `# 3D plotting` `fig ` `=` `plt.figure()` `# using fig.gca, we are creating a 3D` `# projection plot in the empty figure` `ax ` `=` `fig.gca(projection` `=` `"3d"` `)` `# Creating a wireframe plot with the x,y and` `# z-coordinates respectively along with the` `# color as red` `surf ` `=` `ax.plot_wireframe(x, y, z, color` `=` `"red"` `)` `# Creating a wireframe plot with the points` `# x1,y1,z1 along with the plot line as green` `surf1 ` `=` `ax.plot_wireframe(x1, y1, z1, color` `=` `"green"` `)` `#showing the above plot` `plt.show()` |

**Output:**

**Explanation:**

- In this example, we are importing two packages
**matplotlib.pyplot**from python.**NumPy** - After that, we are creating a wide range of values with various variables such as x, y,x1,x2. Now there is a catch over here. The first set of x,y have values from -5 to 5 with each of the elements having a difference of 1 from each other. The second set of elements also ranges from -5 to 5 with each element having a difference of 0.6 from each other. The difference that it creates is, the first graph will have steep curves since the difference between the points is more, whereas, in the second set, the graph will be smoother as compared to the first one because we are taking a wide range of points more than x and y. That’s why the second curve(cosine curve) is smoother than the first curve.
- Using
*meshgrid*, we are returning coordinate matrices from coordinate vectors.*MeshGrid*makes N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, where there is a 1-Dimensional array. Now, we are creating the sine and the cosine curves with the help of z and z1 respectively. - After that, we are creating an empty figure where we will be plotting out 3D plot. Using
__fig.gca,__we are defining that the plots that we are going to make will be of 3D projection using**projection=’3d’**. Using*plot_wireframe*we are creating a 3D sine and cosine curve(of different colors) with the above points created by us. Finally, we are showing the above plot.

**Example 3:**

In the last and the final example, we will be creating two 3D graphs in a single figure/canvas, where we will be our 3D points. So let us move into our code implementation.

## Python3

`#importing matplotlib.pyplot from` `# python` `import` `matplotlib.pyplot as plt` `# importing numpy package from python` `import` `numpy as np` `# creating an empty figure for plotting` `fig ` `=` `plt.figure()` `# defining a sub-plot with 1x2 axis and defining` `# it as first plot with projection as 3D` `ax ` `=` `fig.add_subplot(` `1` `, ` `2` `, ` `1` `, projection` `=` `'3d'` `)` `# creating a range of 12 elements in both` `# X and Y` `X ` `=` `np.arange(` `12` `)` `Y ` `=` `np.linspace(` `12` `, ` `1` `)` `# Creating a mesh grid of X and Y` `X, Y ` `=` `np.meshgrid(X, Y)` `# Creating an expression X and Y and` `# storing it in Z` `Z ` `=` `X` `*` `2` `+` `Y` `*` `3` `;` `# Creating a wireframe plot with the 3 sets of` `# values X,Y and Z` `ax.plot_wireframe(X, Y, Z)` `# Creating my second subplot with 1x2 axis and defining` `# it as the second plot with projection as 3D` `ax ` `=` `fig.add_subplot(` `1` `, ` `2` `, ` `2` `, projection` `=` `'3d'` `)` `# defining a set of points for X,Y and Z` `X1 ` `=` `[` `1` `,` `2` `,` `1` `,` `4` `,` `3` `,` `2` `,` `7` `,` `5` `,` `9` `]` `Y1 ` `=` `[` `8` `,` `2` `,` `7` `,` `4` `,` `3` `,` `6` `,` `1` `,` `8` `,` `9` `]` `Z1 ` `=` `[` `1` `,` `2` `,` `4` `,` `7` `,` `9` `,` `6` `,` `7` `,` `6` `,` `9` `]` `# Plotting 3 points X1,Y1,Z1 with` `# color as green` `ax.plot(X1, Y1, Z1,color` `=` `'green'` `)` `# Showing the above plot` `plt.show()` |

**Output:**

**Explanation:**

- In the above example, we will be working with 2 3D graphs. So for that, we will be creating two subplots in a single canvas or figure. In the code, we have initialized the packages
*matplotlib.pyplot*, - Then we are creating an empty figure where two 3D plots will be plotted. Now we are creating the first subplot.
- After that, we are taking X, Y which contain a series of points, and with them, we are creating a
*meshgrid*which is made up of two 1D dimensional arrays and is used for matrix indexing to create an nD array. - Then, using the values of X and Y, we are creating Z by forming an expression. Using
*plot_wireframe*we are plotting the points in the 3D axis. - After that, we move to the second plot, where we define the 2nd subplot parameters.
- Then, we are creating a wide range of elements and storing them in the form of arrays in X1, Y1, and Z1.
- After that, we are plotting the graph with the above points, and later we are showing the figure containing the 2 3D graphs.

## Key 3D Plots using Matplotlib:

** **Surface Plot and Tri-surface plots

Here we will look at how to create a surface plot and a tri-surface plot. Here, we are integrating both the plots into a single figure so that we can understand the concept of subplots along with that of plots for a wide range of points to be plotted. So let us move to the implementation of the concept. Unlike wireframe plots, these plot’s surfaces will be filled with color.

**Example:**

## Python3

`#importing matplotlib.pyplot from` `# python` `import` `matplotlib.pyplot as plt` `# importing numpy package from python` `import` `numpy as np` `# creating an empty figure for plotting` `fig ` `=` `plt.figure()` `# defining a sub-plot with 1x2 axis and defining` `# it as first plot with projection as 3D` `ax ` `=` `fig.add_subplot(` `1` `, ` `2` `, ` `1` `, projection` `=` `'3d'` `)` `# creating a range of values for` `# x1,y1 from -1 to 1 with` `# a space of 0.1 between the elements so that` `# we can create a single curve in the plot` `x1` `=` `np.arange(` `-` `1` `,` `1` `,` `0.1` `)` `y1` `=` `np.arange(` `-` `1` `,` `1` `,` `0.1` `)` `# Creating a mesh grid with x ,y and x1,` `# y1 which creates an n-dimensional` `# array` `x1,y1` `=` `np.meshgrid(x1,y1)` `# Creating a cosine function with the` `# range of values from the meshgrid` `z1` `=` `np.cos(x1` `*` `np.pi` `/` `2` `)` `# Creating a wireframe plot with the points` `# x1,y1,z1 along with the plot line as red` `ax.plot_surface(x1, y1, z1, color` `=` `"red"` `)` `# Creating my second subplot with 1x2 axis and defining` `# it as the second plot with projection as 3D` `ax ` `=` `fig.add_subplot(` `1` `, ` `2` `, ` `2` `, projection` `=` `'3d'` `)` `# defining a set of points for X1,Y1 and Z1` `X1 ` `=` `[` `1` `,` `2` `,` `1` `,` `4` `,` `3` `,` `2` `,` `7` `,` `5` `,` `9` `]` `Y1 ` `=` `[` `8` `,` `2` `,` `7` `,` `4` `,` `3` `,` `6` `,` `1` `,` `8` `,` `9` `]` `Z1 ` `=` `[` `1` `,` `2` `,` `4` `,` `7` `,` `9` `,` `6` `,` `7` `,` `6` `,` `9` `]` `# Plotting 3 points X1,Y1,Z1 with` `# color as purple` `ax.plot_trisurf(X1, Y1, Z1,color` `=` `'purple'` `)` `# Showing the above plot` `plt.show()` |

**Output:**

**Explanation:**

- After importing all the necessary packages(
**numpy**,**matplotlib.pyplot**), we are creating an empty figure using*plt.figure(),*we are adding subplots to the above figure where we are taking 1,2,1 as parameters along with the projection as 3D. This enables us to create a plot of 1×2 size, and we define it as the first plot. - Then we are creating a wide range of values from -1 to 1, evenly spaced with a difference of 0.1and storing them in x1 and y1.
- Then, using
*meshgrid*, we are creating an nD array for both x1 and y1. - Using the values of x1 we are creating a cosine curve and storing the set of values in z1.
- With the help of
**ax.plot_surface()**, we are plotting a surface plot defining x1,y1, and z1 points along with the color of the surface plot as red. - After that, we are defining the second plot with the same size i.e 1×2, and defining it as the second plot. We are using variables X1, Y1, and Z1 to create a set of points and store them in these lists.
- Using
**ax.plot_trisurf()**we are defining the points of X1, Y1, and Z1 and the color of the graph as purple. Finally, we are showing the above plot.

### Contour plots and Filled Contour plots

Here, we will be looking at contour and filled contour plots. Since both the plots are similar type, we are using a subplot again for plotting the points. Contour plot is a way of showing a 3D graph by plotting constant z-slices. Filled contour fills the areas that were shown by the line in contour plots.

## Python3

`# importing axes3d from mpl_toolkits.mplot` `# module in python` `from` `mpl_toolkits.mplot3d ` `import` `axes3d` `# importing matplotlib package from python` `import` `matplotlib.pyplot as plt` `#importing numpy package from` `# python library` `import` `numpy as np` `# Creating an empty figure` `fig ` `=` `plt.figure()` `# Creating a subplot where we are` `# defining the projection as 3D projection` `ax ` `=` `fig.add_subplot(` `1` `,` `2` `,` `1` `, projection` `=` `'3d'` `)` `# Creating a set of testing data using` `# get_test_data from axes3d module in` `# python. It creates a set of nD arrays` `# for each of the variables X,Y,Z` `X, Y, Z ` `=` `axes3d.get_test_data(` `0.07` `)` `#Plotting the contour plot with the` `# following range of nD arrays` `plot ` `=` `ax.contour(X, Y, Z)` `# Adding a second subplot in our figure with` `# the projection as a 3D projection` `ax` `=` `fig.add_subplot(` `1` `,` `2` `,` `2` `,projection` `=` `'3d'` `)` `# Adding a range of values to the variables X1,Y1` `X1` `=` `[` `1` `,` `2` `,` `3` `,` `4` `,` `5` `,` `6` `,` `7` `]` `Y1` `=` `[` `1` `,` `2` `,` `3` `,` `4` `,` `5` `,` `6` `,` `7` `]` `# Creating a meshgrid of X1 and Y1` `X1, Y1 ` `=` `np.meshgrid(X1,Y1)` `# Creating an expression for Z1 with the` `# help of X1 and Y1` `Z1` `=` `(X1` `+` `4` `)` `*` `5` `+` `(Y1` `-` `5` `)` `/` `2` `# Creating a contour plot` `plot2 ` `=` `ax.contourf(X1, Y1, Z1)` `# Showing the above plot` `plt.show()` |

**Output:**

**Explanation:**

- The first step is to import all the necessary packages for plotting the above plot. Apart from
**matplotlib.pyplot****NumPy**, we are importing another package which is**mpl_toolkits.mplot3d**. - After that, we are creating an empty figure where we will have our 2 3D subplots.
- After that, we are adding the first subplot of the size 1×2 and define the first subplot.
- After that, we use 3 variables and with the help of
**get_test_data***meshgrid*that will help us to plot the points in the plot. Using**ax.contour(X,Y,Z)** - After that, we define the 2nd plot of the same size. A filled contour plot does
*meshgrid*. It can be created with a simple range of values in X1, Y1, Z1. Z1 is formed with the help of an expression created using X1 and Y1. Using**ax.contourf(X1,Y1,Z1)** - In the end, we are showing the above figure with 2 subplots.

### Polygon plots

Here, we will be exploring a polygon plot. This plot is different from the ones that were plotted in the earlier examples. In this plot, we will be plotting a continuous set of points at different axes points of z. Let’s move to the implementation.

**Example:**

## Python3

`# import Axes3D from mpl_toolkits.mplot3d` `# from python` `from` `mpl_toolkits.mplot3d ` `import` `Axes3D` `# importing PolyCollection from` `# matplotlib.collections module` `from` `matplotlib.collections ` `import` `PolyCollection` `#importing matplotlib.pyplot from` `# python` `import` `matplotlib.pyplot as plt` `# importing numpy package from` `# python` `import` `numpy as np` `# Creating an empty figure` `fig ` `=` `plt.figure()` `# Creating a 3D projection using` `# fig.gca` `ax ` `=` `fig.gca(projection` `=` `'3d'` `)` `# Creating a wide range of elements` `# using numpy package from python` `xs ` `=` `np.arange(` `0` `, ` `1` `, ` `0.1` `)` `# Creating an empty list` `verts ` `=` `[]` `# Creating a range of values on` `# Z-Axis` `zs ` `=` `[` `0.0` `, ` `0.2` `, ` `0.4` `, ` `0.6` `,` `0.8` `]` `# Looping through all the values in zs` `# and creating random values in ys using` `# np.random.rand() which creates a range of` `# elements in ys and we are appending each of them` `# inside verts[]` `for` `z ` `in` `zs:` ` ` `ys ` `=` `np.random.rand(` `len` `(xs))` ` ` `verts.append(` `list` `(` `zip` `(xs, ys)))` `# using polycollection, we are providing a` `# series of vertices to poly so as to` `# plot our required plot` `poly ` `=` `PolyCollection(verts)` `# Using add_collection3d, we are plotting` `# ur required polygon plot where we define` `# zs with the range of values we defined in our` `# list zs and also the zdir as Y-Axis` `ax.add_collection3d(poly,zs` `=` `zs,zdir` `=` `'y'` `)` `# Showing the required plot` `plt.show()` |

**Output:**

**Explanation:**

- In this example, we need to import 4 different packages to create this plot
*(*).**Numpy, matplotlib.pyplot, polycollection,Axes3d** - After that, we will be creating an empty figure where we will plot the above graph. Using
*arange*and a series of some of the arbitrary values we are creating a list of values in x and z.now we are*loopinf*through z where for each value of z we are getting a random list of numbers for y of the same length as that of x. - Now for each z, we are plotting x vs y along the line. Using
*PolyCollection*, we are taking all the plots together with the same color in each of the plot. With the help of*add_collection3d*we are determining that the plot is to be plotted in the x-z axis and also defining zs=0. - Finally, we are showing the above plot.

### Quiver plots

Here, we will be learning about the quiver plot in matplotlib. A quiver plot helps us to plot a 3d field of arrows in order to define the specified points. We can customize the arrows in various ways. Let us look into the code implementation.

**Example:**

## Python3

`# import axes3d from mpl_toolkits.mplot3d` `from` `mpl_toolkits.mplot3d ` `import` `axes3d` `# import matplotlib.pyplot from python` `import` `matplotlib.pyplot as plt` `# import numpy from python` `import` `numpy as np` `# Creating an empty figure` `# to plot a 3D graph` `fig ` `=` `plt.figure()` `# Creating a 3Dprojection for` `# our 3D plots using fig.gca` `ax ` `=` `fig.gca(projection` `=` `'3d'` `)` `# Creating a meshgrid for the range` `# of values in X,Y,Z` `x, y, z ` `=` `np.meshgrid([` `1` `,` `2` `,` `5` `,` `2` `,` `4` `,` `8` `,` `3` `,` `3` `,` `1` `],[` `6` `,` `4` `,` `3` `,` `1` `,` `6` `,` `2` `,` `7` `,` `8` `,` `2` `],[` `1` `,` `2` `,` `5` `,` `2` `,` `4` `,` `8` `,` `3` `,` `3` `,` `1` `])` `# Creating expressions for u,v,w` `# with the help of x,y and z` `# which will form the direction vectors` `u ` `=` `x` `*` `2` `+` `y` `*` `3` `+` `z` `*` `3` `v ` `=` `(x` `+` `3` `)` `*` `(y` `+` `5` `)` `*` `(z` `+` `7` `)` `w ` `=` `x` `+` `y` `+` `z` `# Creating a quiver plot with length of the direction` `# vector length as 0.2 ad normalise as true` `ax.quiver(x, y, z, u, v, w, length` `=` `0.2` `, normalize` `=` `True` `)` `#showing the above plot` `plt.show()` |

**Output:**

**Explanation:**

- In the above code, we are importing all the necessary packages at the top(
).**matplotlib.pyplot,numpy,mpl_toolkit.mplot3d** - Then we are creating an empty figure with the help of
**plt.figure()****.**With the help of*fig.gca(projection=’3d’),*we are specifying the projection as 3D i.e 3D plotting. - Using
*meshgrid*we are creating an N-D array with X, Y, and Z. In the quiver plot, plotting the points is not the only task. We need to specify the components of the direction of vectors. So for that, we are taking u,v,z which are formed through different expressions created using X, Y, and Z. - Using
we are plotting the quiver plot where we specify the length of each quiver as 0.1 and in order for arrows to be of the same length, we define**ax.quiver()****normalize**as**True**.

** **2D data to be plotted in 3D plots

Here, we will be taking a set of 2D points to be plotted in a specific axis in our 3D plot because we cannot plot a 2D point in a 3D plane with all the coordinates. So a specific axis needs to be defined for plotting the 2D points. So let’s see the code of the plot.

## Python3

`# importing numpy package` `import` `numpy as np` `# importing matplotlib package` `import` `matplotlib.pyplot as plt` `# Creating an empty canvas(figure)` `fig ` `=` `plt.figure()` `# Using the gca function, we are defining` `# the current axes as a 3D projection` `ax ` `=` `fig.gca(projection` `=` `'3d'` `)` `# Labelling X-Axis` `ax.set_xlabel(` `'X-Axis'` `)` `# Labelling Y-Axis` `ax.set_ylabel(` `'Y-Axis'` `)` `# Labelling Z-Axis` `ax.set_zlabel(` `'Z-Axis'` `)` `# Creating 10 values for X` `x ` `=` `[` `1` `,` `1.2` `,` `1.4` `,` `1.6` `,` `1.8` `,` `2.0` `,` `2.2` `,` `2.4` `,` `2.6` `,` `2.8` `]` `# Creating 10 values for Y` `y ` `=` `[` `1` `,` `1.2` `,` `1.4` `,` `1.6` `,` `1.8` `,` `2.0` `,` `2.2` `,` `2.4` `,` `2.6` `,` `2.8` `]` `# Creating 10 random values for Y` `z` `=` `[` `1` `,` `2` `,` `4` `,` `5` `,` `6` `,` `7` `,` `8` `,` `9` `,` `10` `,` `11` `]` `# zdir='z' fixes all the points to zs=0 and` `# (x,y) points are ploted in the x-y axis` `# of the graph` `ax.plot(x, y, zs` `=` `0` `, zdir` `=` `'z'` `)` `# zdir='y' fixes all the points to zs=0 and` `# (x,y) points are ploted in the x-z axis of the` `# graph` `ax.plot(x, y, zs` `=` `0` `, zdir` `=` `'y'` `)` `# Showing the above plot` `plt.show()` |

**Output:**

**Explanation:**

- In this example, we are plotting 2D data on a 3D plot in Matplotlib. For this, we need
**NumPy**andfor creating the set of values and plotting them in 3D projection. After importing all the necessary packages, we are creating a wide range of values in X, Y, and Z.**matplotlib.pyplot** - Now with the help of
*ax.plot()*we are plotting our 2D points, where we specify the two sets to be plotted as a parameter inside*ax.plot()*along with the axis in which they are to be plotted.