Create Filled Polygon with Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to create a filled polygon using Matplotlib in Python. We will use the Koch snowflake as an example polygon.

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/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/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/FunctionsGroup -.-> python/recursion("`Recursion`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") 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-48737{{"`Create Filled Polygon with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/variables_data_types -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/numeric_types -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/conditional_statements -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/lists -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/tuples -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/dictionaries -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/function_definition -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/default_arguments -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/recursion -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/importing_modules -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/numerical_computing -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/data_visualization -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} python/build_in_functions -.-> lab-48737{{"`Create Filled Polygon with Matplotlib`"}} end

Import Libraries

Before we start, let's import the necessary libraries.

import matplotlib.pyplot as plt
import numpy as np

Define the Koch Snowflake Function

Next, we will define a function to generate the Koch snowflake. The function takes two parameters: the recursion depth and the scale factor.

def koch_snowflake(order, scale=10):
    """
    Return two lists x, y of point coordinates of the Koch snowflake.

    Parameters
    ----------
    order : int
        The recursion depth.
    scale : float
        The extent of the snowflake (edge length of the base triangle).
    """
    def _koch_snowflake_complex(order):
        if order == 0:
            ## initial triangle
            angles = np.array([0, 120, 240]) + 90
            return scale / np.sqrt(3) * np.exp(np.deg2rad(angles) * 1j)
        else:
            ZR = 0.5 - 0.5j * np.sqrt(3) / 3

            p1 = _koch_snowflake_complex(order - 1)  ## start points
            p2 = np.roll(p1, shift=-1)  ## end points
            dp = p2 - p1  ## connection vectors

            new_points = np.empty(len(p1) * 4, dtype=np.complex128)
            new_points[::4] = p1
            new_points[1::4] = p1 + dp / 3
            new_points[2::4] = p1 + dp * ZR
            new_points[3::4] = p1 + dp / 3 * 2
            return new_points

    points = _koch_snowflake_complex(order)
    x, y = points.real, points.imag
    return x, y

Generate a Filled Polygon

Now, we can generate a filled polygon using the fill() function. We will use the Koch snowflake function to generate the coordinates for the polygon.

x, y = koch_snowflake(order=5)

plt.figure(figsize=(8, 8))
plt.axis('equal')
plt.fill(x, y)
plt.show()

Customize the Polygon

We can customize the colors and linewidth of the polygon using keyword arguments in the fill() function.

x, y = koch_snowflake(order=2)

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(9, 3),
                                    subplot_kw={'aspect': 'equal'})
ax1.fill(x, y)
ax2.fill(x, y, facecolor='lightsalmon', edgecolor='orangered', linewidth=3)
ax3.fill(x, y, facecolor='none', edgecolor='purple', linewidth=3)

plt.show()

Summary

In this lab, we learned how to create a filled polygon using Matplotlib in Python. We used the Koch snowflake as an example polygon and demonstrated how to customize the polygon with different colors and linewidths.

Other Python Tutorials you may like