avatarDr. Ashish Bamania

Summary

The undefined website article introduces five lesser-known Matplotlib methods for advanced data visualization in Python.

Abstract

The article "5 Matplotlib Methods That You Never Knew Existed" on the undefined website delves into advanced plotting techniques using Matplotlib, a popular data visualization library in Python. It details the usage of quiver for plotting vector fields, contour and contourf for creating contour plots, cohere for visualizing the coherence between two signals, triplot for triangular grid plotting, and matshow for displaying matrices in a color-coded grid. Each method is accompanied by a brief explanation, usage syntax, example plots, and links to the official Matplotlib documentation for further reading. The article aims to enhance the reader's data visualization toolkit by introducing these powerful, yet often overlooked, plotting functionalities.

Opinions

  • The author suggests that the quiver method is particularly useful for representing physical quantities like electromagnetic fields and fluid dynamics.
  • The contour and contourf methods are presented as effective tools for visualizing 3D data in two dimensions, with contourf being specifically highlighted for its ability to create filled contour plots that show continuous data.
  • The cohere method is recommended for analyzing the frequency domain correlation between two signals, which can be crucial in signal processing.
  • The triplot method is showcased as a means to create triangular grids or subdivisions, which can be particularly useful in finite element analysis or geospatial data representation.
  • The matshow method is touted for its simplicity in displaying matrices, making it a go-to function for heatmaps or other matrix-based visualizations.
  • The author encourages reader interaction by suggesting clapping, commenting, and highlighting parts of the article, indicating a desire for community engagement and feedback.
  • The article concludes with a call to action for readers to subscribe to the author's newsletters and check out their books, implying that the content provided is part of a broader educational initiative by the author.

5 Matplotlib Methods That You Never Knew Existed

1. quiver

Generated with DALL-E 3

1. quiver

The quiver method is used to plot vector fields in matplotlib.

A vector field is a mathematical model of the magnitude and direction of different vectors in a 2D or 3D space.

These are used to represent different physical quantities like:

  • Electromagnetic fields
  • Fluid dynamics, and more

How To Use?

quiver([X, Y], U, V, [C], **kwargs)

The parameters passed to this method are as follows:

  • X, Y: define the x and y coordinates of the arrow locations
  • U, V: define the x and y direction components of the arrow vectors/directions
  • C: sets the colour of the arrows

Example Plot

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 20)
y = np.linspace(0, 2*np.pi, 20)

# Starting positions of the vectors in the vector field
X, Y = np.meshgrid(x, y)

# Horizontal component of the vectors 
U = np.cos(X)

# Vertical component of the vectors
V = np.sin(Y)

plt.quiver(X, Y, U, V)
plt.show()
Quiver plot/ Vector field plot

Documentation

2. contour / contourf

contour method is used to create a Contour plot that visualises 3D data in two dimensions using contour lines.

How To Use?

contour([X, Y,] Z, [levels], **kwargs) 

The parameters passed to this method are as follows:

  • X, Y: define the coordinates of the values in Z
  • Z: define the height values over which the contour is drawn
  • levels: defines the number and positions of the contour lines/regions

Example Plot

import matplotlib.pyplot as plt
import numpy as np

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

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

Z = np.sin(np.sqrt(X**2 + Y**2))

plt.contour(X, Y, Z)
plt.show()
Contour plot of sin(sqrt(X² + Y²))

The contourf method creates filled contour plots that provide a visual representation of continuous data.

import matplotlib.pyplot as plt
import numpy as np

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

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

#Z is a Gaussian function
Z = np.exp(-(X**2 + Y**2))

plt.contourf(X, Y, Z, levels = 20)

plt.colorbar()
plt.show()
Filled Contour Plot of a Gaussian Function

Documentation

3. cohere

The cohere method is used to plot the coherence/ correlation between two signals in the frequency domain.

Mathematically, Coherence is the normalized cross-spectral density as shown below:

Coherence formula

How To Use?

plt.cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None)

The parameters passed to this method are as follows:

  • x, y: Input signals to be analyzed
  • NFFT: The number of data points used in each block for the FFT (Fast Fourier Transform)
  • Fs: The sampling frequency of the input signals
  • Fc: The centre frequency of x
  • detrend: The function applied to each segment before FFT
  • window and noverlap control the computation specifics for FFT

Example Plot

import matplotlib.pyplot as plt
import numpy as np

# Generate two sample signals
t = np.arange(0.0, 5.0, 0.01)
s1 = np.sin(2 * np.pi * t)
s2 = np.sin(2 * np.pi * t + np.pi / 2)

plt.cohere(s1, s2, NFFT=64, Fs=1. / 0.01)

plt.xlabel('Frequency')
plt.ylabel('Coherence')
plt.show()
Coherence Plot

Documentation

4. triplot

The triplot method is used to create a Triangular grid or Triangulations that are subdivisions of a geometric object into triangles.

How To Use?

triplot(triangulation, ...)

#or

triplot(x, y, [triangles], *, [mask=mask], ...)

The parameter to the methods can either be passed a Triangulation object or can be given the points to define a triangular grid (x, y, triangles and a mask).

Example Plot

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

points = np.random.rand(20, 2)

# Delaunay triangulation on the random points
triangulation = tri.Triangulation(points[:, 0], points[:, 1])

plt.triplot(triangulation, 'bo-')

plt.show()
Triplot

Documentation

5. matshow

The matshow method is used to display matrices (2D arrays) as colour-coded grids.

How To Use?

matshow(A, fignum=None, **kwargs)

The parameters passed to the method are as follows:

  • A: the matrix to be displayed
  • fignum: specifies the figure that should be used for the plot

Example Plot

import matplotlib.pyplot as plt
import numpy as np

# Sample matrix
data = np.random.rand(10, 10)

plt.matshow(data)
plt.colorbar() 
plt.show()
Matrix Plot

Documentation

If you found the article valuable and wish to offer a gesture of encouragement:

  1. Clap 50 times for this article
  2. Leave a comment telling me what you think
  3. Highlight the parts in this article that you resonate with

Subscribe to my Substack newsletters below:

Check out my books below:

Data Science
Programming
Data Visualization
Python
Matplotlib
Recommended from ReadMedium