12
Lesson 12
Working with 3D Plots
Objective
By the end of this lesson, students will understand how to create 3D plots using Axes3D from mpl_toolkits.mplot3d. They will be able to create and customize 3D line plots, scatter plots, and surface plots.
1. Introduction to 3D Plotting with Axes3D:
Matplotlib supports 3D plotting, which can be used for visualizing data in three dimensions. To work with 3D plots, we use Axes3D from the mpl_toolkits.mplot3d module.
Steps to create 3D plots:
1. Import Axes3D from mpl_toolkits.mplot3d.
2. Create a 3D axes object using fig.add_subplot() with projection='3d'.
3. Use specific plotting functions (like plot(), scatter(), plot_surface()) to create 3D plots.
Example: Basic 3D setup
By the end of this lesson, students will understand how to create 3D plots using Axes3D from mpl_toolkits.mplot3d. They will be able to create and customize 3D line plots, scatter plots, and surface plots.
1. Introduction to 3D Plotting with Axes3D:
Matplotlib supports 3D plotting, which can be used for visualizing data in three dimensions. To work with 3D plots, we use Axes3D from the mpl_toolkits.mplot3d module.
Steps to create 3D plots:
1. Import Axes3D from mpl_toolkits.mplot3d.
2. Create a 3D axes object using fig.add_subplot() with projection='3d'.
3. Use specific plotting functions (like plot(), scatter(), plot_surface()) to create 3D plots.
Example: Basic 3D setup
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Create a figure and add 3D axes fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Set titles and labels ax.set_title('Basic 3D Plot') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') # Show the plot plt.show()
In this example:
- We create a 3D plot by setting the projection parameter to '3d' when creating the axes object.
- Titles and labels are added to the X, Y, and Z axes.
2. Creating 3D line plots:
A 3D line plot can be created using the plot() function, similar to a 2D plot, but with three sets of data for the X, Y, and Z axes.
Syntax:
ax.plot(x, y, z)
- x : Data for the X-axis.
- y : Data for the Y-axis.
- z : Data for the Z-axis.
Example: 3D line plot
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) z = np.cos(x) # Create a figure and 3D axes fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Create a 3D line plot ax.plot(x, y, z) # Set titles and labels ax.set_title('3D Line Plot') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') # Show the plot plt.show()
In this example:
- A 3D line plot is created by passing X, Y, and Z data to the plot() function.
- The plot visualizes a sinusoidal and cosine relationship between the data points.
3. Creating 3D scatter plots:
A 3D scatter plot can be created using the scatter() function, similar to a 2D scatter plot, but it shows points in three dimensions.
Syntax:
ax.scatter(x, y, z, color, marker)
- x, y, z : Data points for each axis.
- color : Specifies the color of the points.
- marker : Specifies the shape of the scatter points.
Example: 3D scatter plot
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # Create sample data x = np.random.rand(100) y = np.random.rand(100) z = np.random.rand(100) # Create a figure and 3D axes fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Create a 3D scatter plot ax.scatter(x, y, z, color='r', marker='o') # Set titles and labels ax.set_title('3D Scatter Plot') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') # Show the plot plt.show()
In this example:
- We create a 3D scatter plot where 100 random points are scattered across the X, Y, and Z axes.
- The points are displayed in red with circular markers ('o').
4. Creating 3D surface plots:
A 3D surface plot is used to display three-dimensional data as a continuous surface. It can be created using the plot_surface() function. The surface is typically generated from a grid of X and Y values, with corresponding Z values.
Syntax:
ax.plot_surface(X, Y, Z, cmap)
- X, Y : Meshgrid data for the X and Y axes.
- Z : Z values for the surface.
- cmap : Colormap for the surface.
Example: 3D surface plot
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # Create sample data (a grid) x = np.linspace(-5, 5, 50) y = np.linspace(-5, 5, 50) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) # Create a figure and 3D axes fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Create a 3D surface plot ax.plot_surface(X, Y, Z, cmap='viridis') # Set titles and labels ax.set_title('3D Surface Plot') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') # Show the plot plt.show()
In this example:
- A 3D surface plot is created by generating a mesh grid of X and Y values.
- The Z values are calculated based on a mathematical function (a sine wave).
- The cmap parameter is used to apply the colormap 'viridis' to the surface.
5. Customizing 3D plots:
Just like 2D plots, 3D plots can be customized with different colors, markers, line styles, and other parameters to make the visualizations more informative and visually appealing.
Customizing line style and color
ax.plot(x, y, z, color='green', linestyle='dashed')
Customizing scatter point size
ax.scatter(x, y, z, color='blue', s=100) # 's' specifies the size of the points
Using a different colormap for surface plot
ax.plot_surface(X, Y, Z, cmap='plasma') # Change colormap to 'plasma'
6. Exercises:
Exercice: 1
1. Generate X values from 0 to 10, Y values as cos(x), and Z values as sin(x).
2. Create a 3D line plot and label the axes.
Exercice: 2
1. Create a 3D scatter plot. Use 100 random points for X, Y, and Z.
2. Create a 3D scatter plot with blue scatter points of size 50.
Exercice: 3
1. Create a 3D surface plot. Generate a meshgrid from X and Y values ranging from -4 to 4.
2. Use the function Z = X^2 + Y^2 for the Z values.
3. Create a 3D surface plot with a 'coolwarm' colormap.
Exercice: 4
1. Create a 3D plot that includes both a 3D line plot and a 3D scatter plot.
2. Customize the colors and styles of each plot.
Conclusion
In this lesson, we learned how to create and customize 3D plots in Matplotlib using Axes3D. We explored different types of 3D plots, including line plots, scatter plots, and surface plots. Understanding how to visualize data in three dimensions is essential for analyzing more complex datasets. In the next lesson, we will continue to explore advanced plotting techniques with Matplotlib.