Optimization Contour Plotting with Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

This lab will guide you through the process of creating a contour plot using Matplotlib in Python. You will learn how to generate curves with larger values and how to use ~matplotlib.patheffects.TickedStroke to distinguish between the valid and invalid sides of the constraint boundaries.

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/PlotCustomizationGroup(["`Plot Customization`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) 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`") matplotlib/PlotCustomizationGroup -.-> matplotlib/line_styles_colors("`Customizing Line Styles and Colors`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/contour_plots("`Contour Plots`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills python/comments -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} matplotlib/line_styles_colors -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} matplotlib/contour_plots -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/booleans -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/lists -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/tuples -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/importing_modules -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/using_packages -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/standard_libraries -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/numerical_computing -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} python/data_visualization -.-> lab-48631{{"`Optimization Contour Plotting with Matplotlib`"}} end

Import the Required Libraries

To get started, you need to import the necessary libraries. Matplotlib and NumPy are required to create the contour plot.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patheffects

Set Up the Survey Vectors and Matrices

Next, set up the survey vectors and matrices. Design disk loading and gear ratio.

nx = 101
ny = 105

## Set up survey vectors
xvec = np.linspace(0.001, 4.0, nx)
yvec = np.linspace(0.001, 4.0, ny)

## Set up survey matrices.  Design disk loading and gear ratio.
x1, x2 = np.meshgrid(xvec, yvec)

Evaluate the Data to Plot

Now, evaluate some data to plot. In this example, we will plot an objective function, g1, g2, and g3.

## Evaluate some stuff to plot
obj = x1**2 + x2**2 - 2*x1 - 2*x2 + 2
g1 = -(3*x1 + x2 - 5.5)
g2 = -(x1 + 2*x2 - 4.5)
g3 = 0.8 + x1**-3 - x2

Create the Contour Plot

Now, create the contour plot using the ax.contour() method. This method is used to represent the topography of the objective function and generate boundary curves of the constraint functions.

fig, ax = plt.subplots(figsize=(6, 6))

cntr = ax.contour(x1, x2, obj, [0.01, 0.1, 0.5, 1, 2, 4, 8, 16], colors='black')
ax.clabel(cntr, fmt="%2.1f", use_clabeltext=True)

cg1 = ax.contour(x1, x2, g1, [0], colors='sandybrown')
plt.setp(cg1.collections, path_effects=[patheffects.withTickedStroke(angle=135)])

cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
plt.setp(cg2.collections, path_effects=[patheffects.withTickedStroke(angle=60, length=2)])

cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
plt.setp(cg3.collections, path_effects=[patheffects.withTickedStroke(spacing=7)])

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)

plt.show()

Interpret the Results

The resulting plot shows the topography of the objective function and the boundary curves of the constraint functions. The ~matplotlib.patheffects.TickedStroke is used to distinguish between the valid and invalid sides of the constraint boundaries.

Summary

In this lab, you learned how to create a contour plot using Matplotlib in Python. You also learned how to generate curves with larger values and how to use ~matplotlib.patheffects.TickedStroke to distinguish between the valid and invalid sides of the constraint boundaries.

Other Python Tutorials you may like