Trusted answers to developer questions

Educative Answers Team

To visualize the relationship between three variables, we generally need a three-dimensional graph. A **contour plot** is a 2D diagram that uses circles (often colored) to represent the third axis. Any point on the circle has the same value in the third axis.

Matplotlib makes it fairly simple to draw contour plots.

We don’t need to import the entire matplotlib module, *pyplot* should be enough. Also, import *numpy* for any mathematics needed for the plot.

from matplotlib import pyplot as plt import numpy as np #For mathematics, and making arrays

width_of_panel = 4 height_of_panel = 3 d = 1000 plt.figure(figsize=(width_of_panel, height_of_panel), dpi=d)

This usually comprises of two independent-variable arrays and a dependent variable array (the contour).

x = np.arange(0, 25, 1) y = np.arange(0, 25, 1) x, y = np.meshgrid(x, y) z = np.sin(x/3) + np.cos(y/4)

plt.contour(x, y, z)

Now, let’s combine all of this to make a simple contour plot.

import matplotlib.pyplot as plt import numpy as np width_of_panel = 4 height_of_panel = 3 d = 1000 plt.figure(figsize=(width_of_panel, height_of_panel), dpi=d) x = np.arange(0, 25, 1) y = np.arange(0, 25, 1) x, y = np.meshgrid(x, y) z = np.sin(x/3) + np.cos(y/4)#np.sin(x * np.pi / 2) + np.cos(y * np.pi / 3) plt.contour(x, y, z)

To make a filled contour plot, just replace `contour`

with `contourf`

.

import matplotlib.pyplot as plt import numpy as np width_of_panel = 4 height_of_panel = 3 d = 1000 plt.figure(figsize=(width_of_panel, height_of_panel), dpi=d) x = np.arange(0, 25, 1) y = np.arange(0, 25, 1) x, y = np.meshgrid(x, y) z = np.sin(x/3) + np.cos(y/4)#np.sin(x * np.pi / 2) + np.cos(y * np.pi / 3) plt.contourf(x, y, z)

RELATED TAGS

contour plot

matplotlib

python

Copyright ©2022 Educative, Inc. All rights reserved

RELATED COURSES

View all Courses

Keep Exploring

Related Courses