Create Interactive Triangulation Plot with Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

This lab will guide you through creating a triangulation plot using Matplotlib. You will learn how to create a Triangulation object, use a TriFinder object, and set up interactivity to highlight the triangle under the cursor.

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/AdvancedTopicsGroup(["`Advanced Topics`"]) 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`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") 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/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills python/comments -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} matplotlib/figures_axes -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} matplotlib/event_handling -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/conditional_statements -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/lists -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/tuples -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/sets -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/function_definition -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/importing_modules -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/using_packages -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/standard_libraries -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/math_random -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/numerical_computing -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} python/data_visualization -.-> lab-49007{{"`Create Interactive Triangulation Plot with Matplotlib`"}} end

Create Triangulation Object

First, we need to create a Triangulation object. We will use the Triangulation class from matplotlib.tri. In this example, we will create a Triangulation object with random data.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.tri import Triangulation

## Generate random data
x = np.random.rand(10)
y = np.random.rand(10)
triang = Triangulation(x, y)

Create TriFinder Object

To find the triangle under the cursor, we need to create a TriFinder object. We can get the default TriFinder object from the Triangulation object using the get_trifinder() method.

trifinder = triang.get_trifinder()

Set up Plot

Now, we can set up the plot. We will use plt.subplots() to create a figure and axis object. Then, we will use ax.triplot() to plot the triangulation.

fig, ax = plt.subplots()
ax.triplot(triang)

Highlight Triangle Under Cursor

We want to highlight the triangle under the cursor as the mouse is moved over the plot. To do this, we will create a Polygon object that will be updated with the vertices of the triangle under the cursor. We will use ax.add_patch() to add the polygon to the plot.

from matplotlib.patches import Polygon

polygon = Polygon([[0, 0], [0, 0], [0, 0]], facecolor='y')
ax.add_patch(polygon)

We will also create a function update_polygon() that will update the vertices of the polygon with the vertices of the triangle under the cursor.

def update_polygon(tri):
    if tri == -1:
        points = [0, 0, 0]
    else:
        points = triang.triangles[tri]
    xs = triang.x[points]
    ys = triang.y[points]
    polygon.set_xy(np.column_stack([xs, ys]))

Set up Interactivity

We need to set up interactivity to update the triangle under the cursor. We will use the motion_notify_event to detect when the mouse is moved over the plot. We will create a function on_mouse_move() that will get the triangle under the cursor using the TriFinder object, update the polygon with the vertices of the triangle, and update the plot title with the index of the triangle.

def on_mouse_move(event):
    if event.inaxes is None:
        tri = -1
    else:
        tri = trifinder(event.xdata, event.ydata)
    update_polygon(tri)
    ax.set_title(f'Triangle {tri}')
    event.canvas.draw()

fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)

Show Plot

Finally, we can show the plot using plt.show().

plt.show()

Summary

In this lab, we learned how to create a triangulation plot using Matplotlib. We used the Triangulation and TriFinder classes to create a triangulation and find the triangle under the cursor. We also set up interactivity to highlight the triangle under the cursor.

Other Python Tutorials you may like