In this tutorial, we’ll try to understand how to create a contour plot in matplotlib.
A contour plot is a type of plot that allows us to visualize three-dimensional data in two dimensions by using contours. Contours are concentric lines that represent a magnitude.
To create a contour plot in matplotib you can use the following methods available in the matplotlib.pyplot
module –
- The
contour
method – used to create contour plots (that are not filled). - The
contourf
method – used to create filled contour plots.
Let’s now look at both the above methods in detail.
Method 1 – Using the matplotlib.pyplot.contour()
method
This method creates contour plots.
Basic Syntax:
matplotlib.pyplot.contour(*args, data=None, **kwargs)
Parameters:
- X, Y: The coordinates of the values in Z. Note that X and Y both must both be 2-D with the same shape as Z (e.g. created via numpy.meshgrid).
- Z: The height values over which the contour is drawn.
- levels: Determines the number and positions of the contour lines/regions.
For more details about the parameters, refer this.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
Now let us understand the above method using some worked out examples.
Example 1 – Draw a simple contour plot
Let’s use the matplotlib.pyplot.contour()
function to create a simple contour plot.
import numpy as np import matplotlib.pyplot as plt #generating x and y values x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40) #creating the meshgrid X, Y = np.meshgrid(x, y) Z = np.sin(X*2) + np.cos(Y*5) #plotting the contour plot plt.contour(X,Y,Z)
Output:
In the above example, we –
- Import the required modules.
- Generate the x and y values using the
numpy.linspace
method (refer this). - Create the meshgrid from the generated x and y values in step 2 using
numpy.meshgrid
(refer this). - Generate the respective Z values using the equation
z = sin(x^2)+cos(y^2)
. - Plot the X, Y, and Z values on a contour plot.
Example 2 – Simple contour plot with customizations
You can also customize the contour plot with additional keyword arguments to the matplotlib.pyplot.contour()
function. For example, let’s plot the above plot again but this time with black colored contours and having a linestyle of “dashdot”.
import numpy as np import matplotlib.pyplot as plt #generating x and y values x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40) #creating the meshgrid X, Y = np.meshgrid(x, y) Z = np.sin(X*2) + np.cos(Y*5) #plotting the contour plot plt.contour(X,Y,Z,colors = 'black', linestyles='dashdot')
Output:
Now, the contour plot is formatted according to our customizations.
Example 3 – Simple contour plot with specifying levels
You can also choose the number of contour lines to use with the levels
parameter. For example, if you pass n
as an integer to the levels
parameter, the contours will have n
intervals.
Let’s look at an example.
import numpy as np import matplotlib.pyplot as plt #generating x and y values x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40) #creating the meshgrid X, Y = np.meshgrid(x, y) Z = np.sin(X*2) + np.cos(Y*5) #plotting the contour plot plt.contour(X,Y,Z, levels=10, cmap='Blues')
Output:
In this example, we set the levels
to 10
and use the Blues
cmap for the contour lines.
Method 2 – Using the matplotlib.pyplot.contourf()
method
If you want to create filled contour plots in matplotlib, use the matpltolib.pyplot.contourf()
function. The parameters of this function are similar to the matplotlib.pyplot.contour()
function.
Basic Syntax:
matplotlib.pyplot.contourf(*args, data=None, **kwargs)
Parameters:
- X, Y: The coordinates of the values in Z.
- Z: The height values over which the contour is drawn.
- levels: Determines the number and positions of the contour lines/regions.
For more details about the parameters, refer this.
Now let us understand this method with the help of some worked out examples.
Example 1 – Simple filled contour plot
Let’s plot a simple filled contour plot.
import numpy as np import matplotlib.pyplot as plt #generating x and y values x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40) #creating the meshgrid X, Y = np.meshgrid(x, y) Z = np.sin(X*2) + np.cos(Y*5) #plotting the contour plot plt.contourf(X,Y,Z)
Output:
In the above example, we –
- Import the required modules.
- Generate the x and y values using the
numpy.linspace
method (refer this). - Create the meshgrid from the generated x and y values in step 2 using
numpy.meshgrid
(refer this). - Generate the respective Z values using the equation
z = sin(x^2)+cos(y^2)
. - Plot the X, Y, and Z values on a filled contour plot.
Example 2 – Simple contour plot with customizations
Similar to the contourf()
function, you can custom format the filled contour plots with the contourf()
function using additional arguments.
For example, let’s plot the above graph again but this time using a red color map.
import numpy as np import matplotlib.pyplot as plt #generating x and y values x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40) #creating the meshgrid X, Y = np.meshgrid(x, y) Z = np.sin(X*2) + np.cos(Y*5) #plotting the contour plot plt.contourf(X,Y,Z,cmap='Reds')
Output:
Example 3 – Add a color bar to contour plot
You can use the matplotlib.pyplot.colorbar()
function to add a color bar to a plot in matplotib. Let’s add a color bar to the plot above.
import numpy as np import matplotlib.pyplot as plt #generating x and y values x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40) #creating the meshgrid X, Y = np.meshgrid(x, y) Z = np.sin(X*2) + np.cos(Y*5) #plotting the contour plot plt.contourf(X,Y,Z,cmap='Reds') plt.colorbar()
Output:
The color bar shows the magnitude of the values represented by the different shades of the color.
You might also be interested in –
- Pandas – Plot Multiple Dataframes in Subplots
- How to Create Multiple Matplotlib Plots in One Figure?
- How To Make a Bubble Plot in Python with Matplotlib?
- Matplotlib – Create a Plot with two Y Axes and shared X Axis
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.