Create 3D Polygon Fills for Line Graphs

PythonPythonBeginner
Practice Now

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

Introduction

In this tutorial, we will learn how to create polygons which fill the space under a line graph in a 3D plot using Python's Matplotlib library. The polygons will be semi-transparent, creating a sort of 'jagged stained glass' effect.

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`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") 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-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} matplotlib/importing_matplotlib -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} matplotlib/figures_axes -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/variables_data_types -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/for_loops -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/list_comprehensions -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/lists -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/tuples -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/function_definition -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/lambda_functions -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/importing_modules -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/using_packages -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/standard_libraries -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/math_random -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/data_collections -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/numerical_computing -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/data_visualization -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} python/build_in_functions -.-> lab-48879{{"`Create 3D Polygon Fills for Line Graphs`"}} end

Import the Required Libraries

We will begin by importing the necessary libraries.

import math
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import PolyCollection

Define the Polygon Under Graph Function

Next, we define a function polygon_under_graph(x, y) which constructs the vertex list that defines the polygon filling the space under the (x, y) line graph. This function assumes that x is in ascending order.

def polygon_under_graph(x, y):
    """
    Construct the vertex list which defines the polygon filling the space under
    the (x, y) line graph. This assumes x is in ascending order.
    """
    return [(x[0], 0.), *zip(x, y), (x[-1], 0.)]

Create the 3D Plot

We will now create a 3D plot using Matplotlib.

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

Define the x and lambda Arrays

We define the x and lambda arrays using the linspace and range functions respectively.

x = np.linspace(0., 10., 31)
lambdas = range(1, 9)

Compute the Vertices and Facecolors

We compute the vertices and facecolors using the vectorize and colormaps functions from Matplotlib.

## verts[i] is a list of (x, y) pairs defining polygon i.
gamma = np.vectorize(math.gamma)
verts = [polygon_under_graph(x, l**x * np.exp(-l) / gamma(x + 1))
         for l in lambdas]
facecolors = plt.colormaps['viridis_r'](np.linspace(0, 1, len(verts)))

Create the Polygons and Add to the Plot

We create the polygons using the PolyCollection function from Matplotlib and add them to the plot.

poly = PolyCollection(verts, facecolors=facecolors, alpha=.7)
ax.add_collection3d(poly, zs=lambdas, zdir='y')

Set the Plot Limits and Labels

Finally, we set the plot limits and labels using the set function.

ax.set(xlim=(0, 10), ylim=(1, 9), zlim=(0, 0.35),
       xlabel='x', ylabel=r'$\lambda$', zlabel='probability')

Show the Plot

We display the plot using the show function.

plt.show()

Summary

In this tutorial, we learned how to create polygons which fill the space under a line graph in a 3D plot using Python's Matplotlib library. We used the PolyCollection function to create the polygons and set the plot limits and labels using the set function.

Other Python Tutorials you may like