Matplotlib 2D Data on 3D Plot

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab demonstrates how to plot 2D data on selective axes of a 3D plot using ax.plot's zdir keyword. The matplotlib library in Python is used to create the 3D plot.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/PlottingDataGroup -.-> matplotlib/scatter_plots("`Scatter Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} matplotlib/importing_matplotlib -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} matplotlib/figures_axes -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} matplotlib/line_plots -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} matplotlib/scatter_plots -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} matplotlib/legend_config -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/variables_data_types -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/for_loops -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/lists -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/tuples -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/importing_modules -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/standard_libraries -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/math_random -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/data_collections -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/numerical_computing -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/data_visualization -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} python/build_in_functions -.-> lab-48528{{"`Matplotlib 2D Data on 3D Plot`"}} end

Import Libraries

The first step is to import the necessary libraries. We need matplotlib and numpy to plot the 3D graph.

import matplotlib.pyplot as plt
import numpy as np

Create a 3D Plot

The second step is to create a 3D plot using ax = plt.figure().add_subplot(projection='3d').

ax = plt.figure().add_subplot(projection='3d')

Plot 2D Data on the 3D Plot

The third step is to plot 2D data on the 3D plot using ax.plot and ax.scatter. The ax.plot function plots a sin curve using the x and y axes. The ax.scatter function plots scatterplot data on the x and z axes.

## Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x, y)')

## Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')

## Fixing random state for reproducibility
np.random.seed(19680801)

x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
    c_list.extend([c] * 20)
## By using zdir='y', the y value of these points is fixed to the zs value 0
## and the (x, y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x, z)')

Customize the Plot

The fourth step is to customize the plot by adding a legend, setting axes limits and labels, and changing the view angle.

## Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

## Customize the view angle so it's easier to see that the scatter points lie
## on the plane y=0
ax.view_init(elev=20., azim=-35, roll=0)

plt.show()

View the Plot

The final step is to view the 3D plot by running the code.

Summary

In this lab, we learned how to plot 2D data on selective axes of a 3D plot using ax.plot's zdir keyword. We also learned how to customize the plot by adding a legend, setting axes limits and labels, and changing the view angle.

Other Python Tutorials you may like