Contour Plot using Matplotlib
Contour Plot using Matplotlib
Mathematics Practical
Contour plots also called level plots are a tool for doing multivariate analysis and visualizing 3-D plots in
2-D space. If we consider X and Y as our variables, we want to plot then the response Z will be plotted as
slices on the X-Y plane due to which contours are sometimes referred as Z-slices or iso-response.
Contour plots are widely used to visualize density, altitudes or heights of the mountain as well as in the
meteorological department. Due to such wide usage matplotlib.pyplot provides a method contour to
make it easy for us to draw contour plots.
matplotlib.pyplot.contour
The matplotlib.pyplot.contour() are usually useful when Z = f(X, Y) i.e Z changes as a function of input X
and Y. A contourf() is also available which allows us to draw filled contours.
Parameters:
X, Y: 2-D numpy arrays with same shape as Z or 1-D arrays such that len(X)==M and len(Y)==N (where M
and N are rows and columns of Z)
Z: The height values over which the contour is drawn. Shape is (M, N)
levels: Determines the number and positions of the contour lines / regions.
Returns: QuadContourSet
Example #1: Plotting of Contour using contour() which only plots contour lines.
import numpy as np
import matplotlib.pyplot as plt
# Define the function
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
# Create a grid of x and y values
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
# Calculate the function values for each point on the grid
Z = f(X, Y)
# Create the contour plot
fig, ax = plt.subplots()
contour = ax.contour(X, Y, Z)
# Add labels and title
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("Contour Plot using contour()")
# Display the plot
plt.show()
#output:
Example #2: Plotting of contour using contourf() which plots filled contours
Sol.:-
import numpy as np
import matplotlib.pyplot as plt
# Add a colorbar
fig.colorbar(contourf)
import numpy as np
How it Works
1. Import Libraries: Import necessary libraries: matplotlib.pyplot for plotting and numpy for
numerical operations.
2. Create Figure and Axes: Create a figure and a 3D subplot
using fig.add_subplot(projection="3d").
3. Create Meshgrid: Generate a meshgrid of x and y values using np.meshgrid.
4. Plot Wireframe: Plot the wireframe using ax.plot_wireframe(). Provide the x, y, and z
coordinates (calculated from your function) as arguments. You can customize the appearance
(color, line style, etc.) using optional parameters.
5. Set Labels and Title: Label the axes and set the title
using ax.set_xlabel, ax.set_ylabel, ax.set_zlabel, and ax.set_title.
6. Display: Show the plot using plt.show().
Surface Plots
Surface plots represent a 3D surface by using a color-mapped surface to visualize the values.
They give a more solid and filled representation of the surface
Here's how to create a surface plot using
plot_surface():