![]() |
|
[Tut] Matplotlib 3D Plot – A Helpful Illustrated Guide - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Matplotlib 3D Plot – A Helpful Illustrated Guide (/thread-94396.html) |
[Tut] Matplotlib 3D Plot – A Helpful Illustrated Guide - xSicKxBot - 04-03-2020 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 Code: import matplotlib.pyplot as pltCode: plt.show()
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()![]() 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()![]() 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![]() 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()![]() 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()![]() 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:
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()![]() 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()![]() 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()![]() 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()![]() 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()![]() 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 |