English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matplotlib Contour Plot

Contour plots (sometimes called 'horizontal plots') are a method to display a three-dimensional surface on a two-dimensional plane. It draws two predicted variables X Y on the y-axis and the response variable Z of the contour. These contours are sometimes called z-slices or isoresponses.

Contour plots are very useful if you want to see how Z changes with the two input X and Y, for example, Z = f(X, Y). The contour lines or isoclines of a two-variable function are curves where the function has a constant value.

The independent variables x and y are usually limited to a regular grid called meshgrid. numpy.meshgrid creates a rectangular grid using the x value array and y value array.

The Matplotlib API includes the contour() and contourf() functions for drawing outlines and filled contours separately. Both functions require three parameters x, y, and z.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
import numpy as np
 import matplotlib.pyplot as plt
 xlist = np.linspace(-3.0, 3.0, 100)
 ylist = np.linspace(-3.0, 3.0, 100)
 X, Y = np.meshgrid(xlist, ylist)
 Z = np.sqrt(X**2 + Y**2)
 fig, ax = plt.subplots(1,1)
 cp = ax.contourf(X, Y, Z)
 fig.colorbar(cp)  # Add a colorbar to a plot
 ax.set_title('Matplotlib Contour Plot')
 #ax.set_xlabel('x (cm)')
 ax.set_ylabel('y (cm)')
 plt.show()

Execute the above example code to get the following result -