0% found this document useful (0 votes)
5 views

Contour Plot using Matplotlib

The document provides an overview of creating contour plots, wireframe plots, and surface plots using the Matplotlib library in Python. It explains the syntax and parameters for the contour function, along with examples for both contour and filled contour plots. Additionally, it outlines the steps to create wireframe and surface plots, including necessary imports and plotting techniques.

Uploaded by

gangurdesahil52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Contour Plot using Matplotlib

The document provides an overview of creating contour plots, wireframe plots, and surface plots using the Matplotlib library in Python. It explains the syntax and parameters for the contour function, along with examples for both contour and filled contour plots. Additionally, it outlines the steps to create wireframe and surface plots, including necessary imports and plotting techniques.

Uploaded by

gangurdesahil52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

MTC-243

Python Prog. Language

Mathematics Practical

Contour Plot using Matplotlib – Python

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.

Syntax: matplotlib.pyplot.contour([X, Y, ] Z, [levels], **kwargs)

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

Below examples illustrate the matplotlib.pyplot.contour() function in matplotlib.pyplot:

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

# 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 filled contour plot


fig, ax = plt.subplots()
contourf = ax.contourf(X, Y, Z)

# Add labels and title


ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("Filled Contour Plot using contourf()")

# Add a colorbar
fig.colorbar(contourf)

# Display the plot


plt.show()
#Output:-
Wireframes and Surface Plots

• Wireframes and Surface Plots


Wireframe plots represent a 3D surface by drawing a mesh of lines. They provide a skeletal view
of the surface, showing the connections between data points.
Here's how to create a wireframe plot using
plot_wireframe():

import matplotlib.pyplot as plt

import numpy as np

# Create the figure and axes object


fig = plt.figure()
ax = fig.add_subplot(projection="3d")

# Create the meshgrid


x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)

# Plot the surface


ax.plot_wireframe(X, Y, np.sin(X) * np.cos(Y), color='blue')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('Wireframe Plot')

# Display the plot


plt.show()
#Output:

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():

import matplotlib.pyplot as plt


import numpy as np

# Create the figure and axes object


fig = plt.figure()
ax = fig.add_subplot(projection="3d")

# Create the meshgrid


x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)

# Plot the surface


ax.plot_surface(X, Y, np.sin(X) * np.cos(Y), cmap='viridis')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('Surface Plot')

# Display the plot


plt.show()
#Outpt:
How it Works
1. Import Libraries: Import matplotlib.pyplot and numpy as in the wireframe example.
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 Surface: Plot the surface using ax.plot_surface(). Provide the x, y, and z coordinates
(calculated from your function) as arguments. You can customize the appearance (color map,
shading, 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().

You might also like