# Plotting Multivariate Functions in Python with Matplotlib: A Comprehensive Guide

Rate this post

π‘ Problem Formulation: You need to visualize a multivariate function which involves more than one variable to understand the interactions between the variables and the resultant function space. For instance, given a function f(x, y) representing some physical phenomena or data, you’d like to produce a 2D or 3D plot that illustrates how f behaves as x and y vary. The goal of this article is to showcase various methods for plotting such functions using Python’s Matplotlib library.

## Method 1: Using Contour Plots for 2D Visualization

Contour plots are valuable for visualizing a three-dimensional dataset on a two-dimensional graph. They indicate where the function has constant values through contour lines, analogous to a topographic map. Matplotlib provides the `contour` and `contourf` functions for creating these plots, which are particularly useful when dealing with functions of two variables.

Here’s an example:

```import numpy as np
import matplotlib.pyplot as plt

def my_function(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)

x = np.linspace(0, 3, 100)
y = np.linspace(0, 3, 100)

X, Y = np.meshgrid(x, y)
Z = my_function(X, Y)

plt.contour(X, Y, Z, colors='black')
plt.show()
```

The output will display a 2D contour plot, showing the undulations of the function through lines of equal value.

This code snippet creates a contour plot for our multivariate function. The `np.meshgrid` function creates coordinate matrices from the coordinate vectors, which we use to evaluate the function `my_function` over a grid. The result is passed to `plt.contour` to draw the contour lines, and then displayed with `plt.show()`.

## Method 2: Plotting a Surface in 3D

To visualize multivariate functions in a more intuitive fashion, a 3D surface plot can be employed. This rendering allows us to understand the variations along the range of both input variables and their corresponding function value, offering insights into the behavior of the function across its domain. Matplotlib’s `Axes3D` object in conjunction with the `plot_surface` function creates vivid 3D representations of such data.

Here’s an example:

```from mpl_toolkits.mplot3d import Axes3D

def my_function(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = my_function(X, Y)

fig = plt.figure()
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis')

plt.show()
```

The output is a 3D surface plot, showing a colorful landscape that represents the function’s behavior in three dimensions.

In this example, we define `my_function` and create a 3D surface plot of it. A figure object is instantiated and a 3D subplot is added to it. The `plot_surface` method is then invoked on the Axes3D object to render our function’s output grid `Z` over the two input grids, `X` and `Y`.

## Method 3: Density and Color Meshes

When it comes to plotting a multivariate function, sometimes the focus is on the gradient or density rather than the surface features. A density plot can show the variations in the function’s value across the inputs using colors. In Matplotlib, the `pcolormesh` function is used for plotting a pseudocolor mesh, which effectively communicates these gradual changes through a color scale.

Here’s an example:

```plt.pcolormesh(X, Y, Z, shading='auto', cmap='viridis')
plt.colorbar()  # Shows the color scale.
plt.show()
```

The output will present a color grid plot with the function’s values represented by a color scale on the side.

The code snippet shows a pseudocolor plot where each cell in the mesh is colored according to the value of the function `Z`. The `shading='auto'` argument ensures that the color shading is smooth, and the `plt.colorbar()` function adds a legend indicating how the colors map to function values.

## Method 4: Wireframe Plots

Wireframe plots are a skeletal version of surface plots and can be used when one is interested in the structural outline of the multivariate function rather than a solid surface. They are particularly useful for complex functions with many local extrema or saddle points. Matplotlib’s `plot_wireframe` function can be adapted for this purpose.

Here’s an example:

```ax.plot_wireframe(X, Y, Z, color='black')
plt.show()
```

The generated wireframe plot displays the function as a mesh without solid surfaces, offering a clear view of the high and low points.

This code snippet creates a wireframe plot of the multivariate function using the Axes3D object. By specifying the color as ‘black’, we emphasize the skeletal structure of the function across its domain.

## Bonus One-Liner Method 5: Quick 3D Contour Plot

For a swift and informational visualization of multivariate functions, a 3D contour plot combines the depth of a surface plot with the straightforwardness of contour lines. Matplotlib allows for this through a simple one-liner using the `contour3D` function.

Here’s an example:

```ax.contour3D(X, Y, Z, 50, cmap='binary')
plt.show()
```

This produces a 3D contour plot with 50 layers, each representing a different value of the multivariate function.

The execution of the one-liner `ax.contour3D` within a 3D axis environment creates a layered plot, where each contour line indicates an iso-surface of the given multivariate function, allowing the viewer to grasp the function’s topology at a glance.

## Summary/Discussion

• Method 1: Contour Plots for 2D Visualization. Strengths: Good for understanding the function at a value level, easily captures local extrema. Weaknesses: Lacks depth, might be hard to interpret in areas with close contour lines.
• Method 2: 3D Surface Plot. Strengths: Visually appealing, provides an intuitive understanding of function behavior, can represent complex structures. Weaknesses: Can be computationally intensive, difficult to visualize when functions are dense.
• Method 3: Density and Color Meshes. Strengths: Clearly displays gradients and density through color, useful for identifying regions of interest. Weaknesses: Does not provide structural insights that come from a 3D view.
• Method 4: Wireframe Plots. Strengths: Lightweight and provides clear structural view of the function. Weaknesses: Can be difficult to interpret without surface shading, might clutter for complex functions.
• Method 5: Quick 3D Contour Plot. Strengths: Fast to implement, elegant blend of contour and 3D plot. Weaknesses: May become confusing with too many layers, less detailed compared to surface plots.