matplotlib

Topics related to matplotlib:

Getting started with matplotlib

Overview

matplotlib is a plotting library for Python. It provides object-oriented APIs for embedding plots into applications. It is similar to MATLAB in capacity and syntax.

It was originally written by J.D.Hunter and is actively being developed. It is distributed under a BSD-Style License.

Three-dimensional plots

Three-dimensional plotting in matplotlib has historically been a bit of a kludge, as the rendering engine is inherently 2d. The fact that 3d setups are rendered by plotting one 2d chunk after the other implies that there are often rendering issues related to the apparent depth of objects. The core of the problem is that two non-connected objects can either be fully behind, or fully in front of one another, which leads to artifacts as shown in the below figure of two interlocked rings (click for animated gif):

3d plot of two interlocked rings showing artifact

This can however be fixed. This artefact only exists when plotting multiple surfaces on the same plot - as each is rendered as a flat 2D shape, with a single parameter determining the view distance. You will notice that a single complicated surface does not suffer the same problem.

The way to remedy this is to join the plot objects together using transparent bridges:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import erf

fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.arange(0, 6, 0.25)
Y = np.arange(0, 6, 0.25)
X, Y = np.meshgrid(X, Y)

Z1 = np.empty_like(X)
Z2 = np.empty_like(X)
C1 = np.empty_like(X, dtype=object)
C2 = np.empty_like(X, dtype=object)

for i in range(len(X)):
  for j in range(len(X[0])):
    z1 = 0.5*(erf((X[i,j]+Y[i,j]-4.5)*0.5)+1)
    z2 = 0.5*(erf((-X[i,j]-Y[i,j]+4.5)*0.5)+1)
    Z1[i,j] = z1
    Z2[i,j] = z2

    # If you want to grab a colour from a matplotlib cmap function, 
    # you need to give it a number between 0 and 1. z1 and z2 are 
    # already in this range, so it just works as is.
    C1[i,j] = plt.get_cmap("Oranges")(z1)
    C2[i,j] = plt.get_cmap("Blues")(z2)


# Create a transparent bridge region
X_bridge = np.vstack([X[-1,:],X[-1,:]])
Y_bridge = np.vstack([Y[-1,:],Y[-1,:]])
Z_bridge = np.vstack([Z1[-1,:],Z2[-1,:]])
color_bridge = np.empty_like(Z_bridge, dtype=object)

color_bridge.fill((1,1,1,0)) # RGBA colour, onlt the last component matters - it represents the alpha / opacity.

# Join the two surfaces flipping one of them (using also the bridge)
X_full = np.vstack([X, X_bridge, np.flipud(X)])
Y_full = np.vstack([Y, Y_bridge, np.flipud(Y)])
Z_full = np.vstack([Z1, Z_bridge, np.flipud(Z2)])
color_full = np.vstack([C1, color_bridge, np.flipud(C2)])

surf_full = ax.plot_surface(X_full, Y_full, Z_full, rstride=1, cstride=1,
                            facecolors=color_full, linewidth=0,
                            antialiased=False)

plt.show()

Two surfaces crossing through one another enter image description here

Figures and Axes Objects

Legends

Integration with TeX/LaTeX

  • Matplotlib’s LaTeX support requires a working LaTeX installation, dvipng (which may be included with your LaTeX installation), and Ghostscript (GPL Ghostscript 8.60 or later is recommended).
  • Matplotlib’s pgf support requires a recent LaTeX installation that includes the TikZ/PGF packages (such as TeXLive), preferably with XeLaTeX or LuaLaTeX installed.

Basic Plots

Multiple Plots

Colormaps

Grid Lines and Tick Marks

Coordinates Systems

Matplotlib has four distinct coordinate systems which can be leveraged to ease the positioning of different object, e.g., text. Each system has a corresponding transformation object which transform coordinates from that system to the so called display coordinate system.

Data coordinate system is the system defined by the data on the respective axes. It is useful when trying to position some object relative to the data plotted. The range is given by the xlim and ylim properties of Axes. Its corresponding transformation object is ax.transData.

Axes coordinate system is the system tied to its Axes object. Points (0, 0) and (1, 1) define the bottom-left and top-right corners of the axes. As such it is useful when positioning relative to the axes, like top-center of the plot. Its corresponding transformation object is ax.transAxes.

Figure coordinate system is analogous to the axes coordinate system, except that it is tied to the Figure. Points (0, 0) and (1, 1) represent the bottom-left and top-right corners of the figure. It is useful when trying to position something relative to the whole image. Its corresponding transformation object is fig.transFigure.

Display coordinate system is the system of the image given in pixels. Points (0, 0) and (width, height) are the bottom-left and top-right pixels of image or display. It can be used for positioning absolutely. Since transformation objects transform coordinates into this coordinate system, display system has no transformation object associated with it. However, None or matplotlib.transforms.IdentityTransform() can be used when necessary.

enter image description here

More details are available here.

Image manipulation

Boxplots

Boxplots

Closing a figure window

Animations and interactive plotting

Histogram

Contour Maps

LogLog Graphing