04-03-2020, 04:47 PM
Matplotlib 3D Plot – A Helpful Illustrated Guide
Are you tired with the same old 2D plots? Do you want to take your plots to the next level? Well look no further, it’s time to learn how to make 3D plots in matplotlib.
In addition to and calling , to create a 3D plot in matplotlib, you need to:
![[Image: img0.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img0.png)
Awesome! You’ve just created your first 3D plot! Don’t worry if that was a bit fast, let’s dive into a more detailed example.
Try it yourself with our interactive Python shell. Just execute the code and look at the generated “plot.png” file:
https://repl.it/@finxter/matplotlib3d?lite=true
Related article:
Matplotlib 3D Plot Example
If you are used to plotting with and notation, making 3D plots in matplotlib is almost identical to creating 2D ones. If you are not comfortable with and plotting notation, check out this article to help you.
Besides the standard, you must also. This imports a 3D object on which a) you can plot 3D data and b) you will make all your plot calls with respect to.
You set up your in the standard way
And add a subplots to that figure using the standard method. If you just want a single , pass to indicate it’s 1 row, 1 column and you are selecting the 1st one. Then you need to pass which tells matplotlib it is a 3D plot.
From now on everything is (almost) the same as 2D plotting. All the functions you know and love such as and accept the same keyword arguments but they now also accept three positional arguments – , and .
In some ways 3D plots are more natural for us to work with since we live in a 3D world. On the other hand, they are more complicated since we are so used to 2D plots. One amazing feature of Jupyter Notebooks is the magic command which, if ran at the top of your notebook, draws all your plots in an interactive window. You can change the orientation by clicking and dragging (right click and drag to zoom in) which can really help to understand your data.
As this is a static blog post, all of my plots will be static but I encourage you to play around in your own Jupyter or IPython environment.
Related article:
Matplotlib 3D Plot Line Plot
Here’s an example of the power of 3D line plots utilizing all the info above.
![[Image: img1.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img1.png)
To avoid repetition, I won’t explain the points I have already made above about imports and setting up the and objects.
I created the variable using which returns an array of 200 numbers between -12 and 12 that are equally spaced out i.e. there is a linear distance between them all. I passed this to and and saved them in variables and .
If you just plotted and now, you would get a circle. To get some up/down movement, you need to modify the z-axis. So, I used again to create a list of 200 numbers equally spaced out between -2 and 2 which can be seen by looking at the z-axis (the vertical one).
Note: if you choose a smaller number of values for the plot is not as smooth.
![[Image: img2.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img2.png)
For this plot, I set the third argument of to 25 instead of 200. Clearly, this plot is much less smooth than the original and hopefully gives you an understanding of what is happening under the hood with these plots. 3D plots can seem daunting at first so my best advice is to go through the code line by line.
Matplotlib 3D Plot Scatter
Creating a scatter plot is exactly the same as making a line plot but you call instead.
Here’s a cool plot that I adapted from this video. If you sample a normal distribution and create a 3D plot from it, you get a ball of points with the majority focused around the center and less and less the further from the center you go.
![[Image: img3.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img3.png)
First, I imported the python random module and set the seed so that you can reproduce my results. Next, I used three list comprehensions to create 3 x 400 samples of a normal distribution using the function. Then I set up the and as normal and made my plot by calling .
![[Image: img4.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img4.png)
In this example, I plotted the same, and lists as in the very first example. I want to highlight to you that some of the points are darker and some are more transparent – this indicates depth. The ones that are darker in color are in the foreground and those further back are more see-through.
If you plot this in IPython or an interactive Jupyter Notebook window and you rotate the plot, you will see that the transparency of each point changes as you rotate.
Matplotlib 3D Plot Rotate
The easiest way to rotate 3D plots is to have them appear in an interactive window by using the Jupyter magic command or using IPython (which always displays plots in interactive windows). This lets you manually rotate them by clicking and dragging. If you right-click and move the mouse, you will zoom in and out of the plot. To save a static version of the plot, click the save icon.
It is possible to rotate plots and even create animations via code but that is out of the scope of this article.
Matplotlib 3D Plot Axis Labels
Setting axis labels for 3D plots is identical for 2D plots except now there is a third axis – the z-axis – you can label.
You have 2 options:
Here is an example using the first method.
![[Image: img5.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img5.png)
Now each axis is labeled as expected.
You may notice that the axis labels are not particularly visible using the default settings. You can solve this by manually increasing the size of the with the argument in your call.
One thing I don’t like about method 1 is that it takes up 3 lines of code and they are boring to type. So, I much prefer method 2.
![[Image: img6.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img6.png)
Much better! Firstly, because you increased the size of the, all the axis labels are clearly visible. Plus, it only took you one line of code to label them all. In general, if you ever use a method in matplotlib, it can be written as instead. This saves you space and is nicer to type, especially if you want to make numerous modifications to the graph such as also adding a title.
Matplotlib 3D Plot Legend
You add legends to 3D plots in the exact same way you add legendsto any other plots. Use the keyword argument and then call at the end.
![[Image: img7.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img7.png)
In this example, I first set the random seed to 1 so that you can reproduce the same results as me. I set up the and as expected, made my first 3D plot using , and and labeled it with the keyword argument and an appropriate string.
To save me from manually creating a brand new dataset, I thought it would be a good idea to make use of the data I already had. So, I applied the function to each of , and which mixes the values of the lists in place. So, calling the second time, plotted the same numbers but in a different order, thus producing a different looking plot. Finally, I labeled the second plot and called to display a legend in the upper left corner of the plot.
All the usual things you can do with legends are still possible for 3D plots. If you want to learn more than these basic steps, check out my comprehensive guide to legends in matplotlib.
Note: If you run the above code again, you will get a different looking plot. This is because you will start with the shuffled, and lists rather than the originals you created further up inb the post.
Matplotlib 3D Plot Background Color
There are two backgrounds you can modify in matplotlib – the and the background. Both can be set using either the or the methods. Hopefully, you know by now that I much prefer the second method over the first!
Here’s an example where I set the background color to green and the background color to red.
![[Image: img8.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img8.png)
The first three lines are the same as a simple line plot. Then I called to set the color to red and to set the color to green.
In an example with one, it looks a bit odd to set the and colors separately. If you have more than one object, it looks much better.
![[Image: img9.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img9.png)
In this example, I used to set up an 8×6 inch containing four 3D objects in a 2×2 grid. The argument accepts a dictionary of values and these are passed to to make each object. For more info on using check out my article.
Then I created the list containing 4 matplotlib color strings. After that, I used a for loop to iterate over and . In order to iterate over and together, they need to be the same shape. There are several ways to do this but using the attribute works well in this case.
Finally, I made the same plot on each and set the facecolors. It is clear now why setting a color can be more useful if you create subplots – there is more space for the color to shine through.
Conclusion
That’s it, you now know the basics of creating 3D plots in matplotlib!
You’ve learned the necessary imports you need and also how to set up your and objects to be 3D. You’ve looked at examples of line and scatter plots. Plus, you can modify these by rotating them, adding axis labels, adding legends and changing the background color.
There is still more to be learned about 3D plots such as surface plots, wireframe plots, animating them and changing the aspect ratio but I’ll leave those for another article.
Where To Go From Here?
Do you wish you could be a programmer full-time but don’t know how to start?
Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back!
https://tinyurl.com/become-a-python-freelancer
It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.
These are proven, no-BS methods that get you results fast.
This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.
https://tinyurl.com/become-a-python-freelancer
Are you tired with the same old 2D plots? Do you want to take your plots to the next level? Well look no further, it’s time to learn how to make 3D plots in matplotlib.
In addition to
Code:
import matplotlib.pyplot as pltCode:
plt.show()- Import the objectCode:
Axes3D
- Initialize your andCode:
FigureobjectsCode:Axes3D
- Get some 3D data
- Plot it using notation and standard function callsCode:
Axes
Code:
# Standard import
import matplotlib.pyplot as plt # Import 3D Axes from mpl_toolkits.mplot3d import axes3d # Set up Figure and 3D Axes fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Get some 3D data
X = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Y = [2, 5, 8, 2, 10, 1, 10, 5, 7, 8]
Z = [6, 3, 9, 6, 3, 2, 3, 10, 2, 4] # Plot using Axes notation and standard function calls
ax.plot(X, Y, Z)
plt.show()![[Image: img0.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img0.png)
Awesome! You’ve just created your first 3D plot! Don’t worry if that was a bit fast, let’s dive into a more detailed example.
Try it yourself with our interactive Python shell. Just execute the code and look at the generated “plot.png” file:
https://repl.it/@finxter/matplotlib3d?lite=true
Related article:
Matplotlib 3D Plot Example
If you are used to plotting with
Code:
FigureCode:
AxesCode:
FigureCode:
AxesBesides the standard
Code:
import matplotlib.pyplot as pltCode:
from mpl_toolkits.mplot3d import axes3dCode:
AxesYou set up your
Code:
FigureCode:
fig = plt.figure()And add a subplots to that figure using the standard
Code:
fig.add_subplot()Code:
AxesCode:
111Code:
projection='3d'From now on everything is (almost) the same as 2D plotting. All the functions you know and love such as
Code:
ax.plot()Code:
ax.scatter()Code:
XCode:
YCode:
ZIn some ways 3D plots are more natural for us to work with since we live in a 3D world. On the other hand, they are more complicated since we are so used to 2D plots. One amazing feature of Jupyter Notebooks is the magic command
Code:
%matplotlib notebookAs this is a static blog post, all of my plots will be static but I encourage you to play around in your own Jupyter or IPython environment.
Related article:
Matplotlib 3D Plot Line Plot
Here’s an example of the power of 3D line plots utilizing all the info above.
Code:
# Standard imports
import matplotlib.pyplot as plt
import numpy as np # Import 3D Axes from mpl_toolkits.mplot3d import axes3d # Set up Figure and 3D Axes fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Create space of numbers for cos and sin to be applied to
theta = np.linspace(-12, 12, 200)
x = np.sin(theta)
y = np.cos(theta) # Create z space the same size as theta z = np.linspace(-2, 2, 200) ax.plot(x, y, z)
plt.show()![[Image: img1.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img1.png)
To avoid repetition, I won’t explain the points I have already made above about imports and setting up the
Code:
FigureCode:
AxesI created the variable
Code:
thetaCode:
np.linspaceCode:
np.sin()Code:
np.cos()Code:
xCode:
yIf you just plotted
Code:
xCode:
yCode:
np.linspaceNote: if you choose a smaller number of values for
Code:
np.linspace![[Image: img2.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img2.png)
For this plot, I set the third argument of
Code:
np.linspaceMatplotlib 3D Plot Scatter
Creating a scatter plot is exactly the same as making a line plot but you call
Code:
ax.scatterHere’s a cool plot that I adapted from this video. If you sample a normal distribution and create a 3D plot from it, you get a ball of points with the majority focused around the center and less and less the further from the center you go.
Code:
import random
random.seed(1) # Create 3 samples from normal distribution with mean and standard deviation of 1
x = [random.normalvariate(1, 1) for _ in range(400)]
y = [random.normalvariate(1, 1) for _ in range(400)]
z = [random.normalvariate(1, 1) for _ in range(400)] # Set up Figure and Axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Plot
ax.scatter(x, y, z)
plt.show()![[Image: img3.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img3.png)
First, I imported the python random module and set the seed so that you can reproduce my results. Next, I used three list comprehensions to create 3 x 400 samples of a normal distribution using the
Code:
random.normalvariate()Code:
FigureCode:
AxesCode:
ax.scatter()Code:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z)
plt.show()![[Image: img4.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img4.png)
In this example, I plotted the same
Code:
XCode:
YCode:
ZIf you plot this in IPython or an interactive Jupyter Notebook window and you rotate the plot, you will see that the transparency of each point changes as you rotate.
Matplotlib 3D Plot Rotate
The easiest way to rotate 3D plots is to have them appear in an interactive window by using the Jupyter magic command
Code:
%matplotlib notebookIt is possible to rotate plots and even create animations via code but that is out of the scope of this article.
Matplotlib 3D Plot Axis Labels
Setting axis labels for 3D plots is identical for 2D plots except now there is a third axis – the z-axis – you can label.
You have 2 options:
- Use the ,Code:
ax.set_xlabel()andCode:ax.set_ylabel()methods, orCode:ax.set_zlabel()
- Use the method and pass it the keyword argumentsCode:
ax.set(),Code:xlabelandCode:ylabel.Code:zlabel
Here is an example using the first method.
Code:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z) # Method 1
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis') plt.show()![[Image: img5.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img5.png)
Now each axis is labeled as expected.
You may notice that the axis labels are not particularly visible using the default settings. You can solve this by manually increasing the size of the
Code:
FigureCode:
figsizeCode:
plt.figure()One thing I don’t like about method 1 is that it takes up 3 lines of code and they are boring to type. So, I much prefer method 2.
Code:
# Set Figure to be 8 inches wide and 6 inches tall
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z) # Method 2 - set all labels in one line of code!
ax.set(xlabel='X axis', ylabel='Y axis', zlabel='Z axis') plt.show()![[Image: img6.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img6.png)
Much better! Firstly, because you increased the size of the
Code:
FigureCode:
ax.set_<something>()Code:
ax.set(<something>=)Matplotlib 3D Plot Legend
You add legends to 3D plots in the exact same way you add legendsto any other plots. Use the
Code:
labelCode:
ax.legend()Code:
import random random.seed(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Plot and label original data
ax.scatter(X, Y, Z, label='First Plot') # Randomly re-order the data
for data in [X, Y, Z]: random.shuffle(data) # Plot and label re-ordered data
ax.scatter(X, Y, Z, label='Second Plot') ax.legend(loc='upper left')
plt.show()![[Image: img7.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img7.png)
In this example, I first set the random seed to 1 so that you can reproduce the same results as me. I set up the
Code:
FigureCode:
AxesCode:
XCode:
YCode:
ZCode:
labelTo save me from manually creating a brand new dataset, I thought it would be a good idea to make use of the data I already had. So, I applied the
Code:
random.shuffle()Code:
XCode:
YCode:
ZCode:
ax.plot()Code:
ax.legend(loc='upper left')All the usual things you can do with legends are still possible for 3D plots. If you want to learn more than these basic steps, check out my comprehensive guide to legends in matplotlib.
Note: If you run the above code again, you will get a different looking plot. This is because you will start with the shuffled
Code:
XCode:
YCode:
ZMatplotlib 3D Plot Background Color
There are two backgrounds you can modify in matplotlib – the
Code:
FigureCode:
AxesCode:
.set_facecolor('color')Code:
.set(facecolor='color')Here’s an example where I set the
Code:
FigureCode:
AxesCode:
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot(X, Y, Z) # Axes color is red
ax.set(facecolor='r')
# Figure color is green
fig.set(facecolor='g')
plt.show()![[Image: img8.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img8.png)
The first three lines are the same as a simple line plot. Then I called
Code:
ax.set(facecolor='r')Code:
AxesCode:
fig.set(facecolor='g')Code:
FigureIn an example with one
Code:
AxesCode:
FigureCode:
AxesCode:
AxesCode:
# Set up Figure and Axes in one function call
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 6), subplot_kw=dict(projection='3d')) colors = ['r', 'g', 'y', 'b'] # iterate over colors and all Axes objects
for c, ax in zip(colors, axes.flat): ax.plot(X, Y, Z) # Set Axes color ax.set(facecolor=c) # Set Figure color
fig.set(facecolor='pink')
plt.show()![[Image: img9.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot/final_html/img/img9.png)
In this example, I used
Code:
plt.subplots()Code:
FigureCode:
AxesCode:
subplot_kwCode:
add_subplotCode:
AxesCode:
plt.subplots()Then I created the list
Code:
colorsCode:
colorsCode:
axes.flatCode:
colorsCode:
axesCode:
.flatFinally, I made the same plot on each
Code:
AxesCode:
FigureConclusion
That’s it, you now know the basics of creating 3D plots in matplotlib!
You’ve learned the necessary imports you need and also how to set up your
Code:
FigureCode:
AxesThere is still more to be learned about 3D plots such as surface plots, wireframe plots, animating them and changing the aspect ratio but I’ll leave those for another article.
Where To Go From Here?
Do you wish you could be a programmer full-time but don’t know how to start?
Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back!
https://tinyurl.com/become-a-python-freelancer
It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.
These are proven, no-BS methods that get you results fast.
This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.
https://tinyurl.com/become-a-python-freelancer

