2D Plotting

There are several ways to visualize 2-Dimensional gridded data using matplotlib.pyplot:

  • How to generate 2-D gridded data from a known math function (meshgrid)
  • Contour
  • Contourf (filled contour) and color bar
  • Pcolormesh (filled grid)
  • Surface (3-D effects)

np.meshgrid

In the following example, we will plot the function $z=exp(-sin(2x)^{2}-cos(2y)^2)-0.5$.

Given each pair of x and y values, z (height) can be computed. Therefore the function z can be plotted on a "map" with axes along x and y using contour or surface.

First we need to generate the data of z using many combinations x and y values covering the ranges of x and y values of interest.

The most efficient way to do this is to specific 1-D arrays of x(0:n) and y(0:m) (for example, using np.linspace), then use np.meshgrid to "expand" the 1-D arrays into 2-D arrays of size (0:m,0:n):

In [1]:
import numpy as np
# let's first use a smaller array to demonstrate what meshgrid does --
x=np.linspace(-1,1,3)
y=np.linspace(-1,1,5)
xx,yy=np.meshgrid(x,y)

print(x)
print(xx.shape)
print(xx)
[-1.  0.  1.]
(5, 3)
[[-1.  0.  1.]
 [-1.  0.  1.]
 [-1.  0.  1.]
 [-1.  0.  1.]
 [-1.  0.  1.]]
In [2]:
print(y)
print(yy.shape)
print(yy)
[-1.  -0.5  0.   0.5  1. ]
(5, 3)
[[-1.  -1.  -1. ]
 [-0.5 -0.5 -0.5]
 [ 0.   0.   0. ]
 [ 0.5  0.5  0.5]
 [ 1.   1.   1. ]]
In [3]:
# Now we use finer grid (larger arrays) to continue our example:
x=np.linspace(-1,1,25)
y=np.linspace(-1,1,25)
xx,yy=np.meshgrid(x,y)
print(xx.shape)

# compute function z using the grids constructed by xx and yy
z=np.exp(-np.sin(2*xx)**2-np.cos(2*yy)**2)-0.5
print(z.shape)
(25, 25)
(25, 25)

plt.contour 畫等值線

CS=plt.contour(x,y,z,cmap=...,levels=...,colors=...)

  • x: array (can be 1D or 2D) of x to evaluate z
  • y: array (can be 1D or 2D) of y to evaluate z
  • z: 2-D array of data to plot contour
  • cmap: color map (remember to import matplotlib.cm)
  • levels: contour levels
  • colors: line color

reference: http://matplotlib.org/api/_as_gen/matplotlib.pyplot.contour.html#matplotlib.pyplot.contour

In [4]:
import matplotlib.pyplot as plt

CS = plt.contour(x, y, z)
plt.title(r'z=exp(-sin(2x)$^2$-cos(2y)$^2$)-0.5')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

plt.contour: change color map 換等值線色階

CS=plt.contour(x,y,z,cmap=...,levels=...,colors=...)

  • cmap: color map (remember to import matplotlib.cm)

Matplotlib provides many pre-defined color map options. Here are some examples:

Use cmap=cm.colormapname in the contour (and contourf) command to change color map. (Default is cm.jet)

More color map choices here: https://matplotlib.org/examples/color/colormaps_reference.html

In [5]:
import matplotlib.cm as cm
CS = plt.contour(x, y, z,cmap=cm.ocean)
plt.show()

plot.label:add contour label 加等值線標籤

plt.clabel(CS, inline=1, fontsize=10)

  • CS: plotting object
  • inline: location of label
    • 1=lines do not cross over label text (default)
    • 0=lines cross over label text
  • fontsize: size of label text
In [6]:
CS = plt.contour(x, y, z,cmap=cm.ocean)
plt.clabel(CS, inline=1, fontsize=10)
plt.show()

plt.contour: change contour levels, single color lines 設定等值線數值、畫單色等值線

CS=plt.contour(x,y,z,cmap=...,levels=...,colors=...)

  • levels: 1D-array to specify contour levels
  • colors: line color (applied to all contour lines. Solid line for positive values, dashed for negative)
    • If None, the colormap specified by cmap will be used.
    • If a string, like ‘r’ or ‘red’, all levels will be plotted in this color.
    • If a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified.
In [7]:
CS = plt.contour(x, y, z, levels=np.linspace(-0.5,0.5,11),colors='r')
plt.clabel(CS,fontsize=7)
plt.show()

plt.contourf: filled contour 色塊等值線(等值線內填入相同顏色)

Similar to contour but fill the space between contours with solid colors.

CS=plt.contourf(x,y,z,cmap=...,levels=...)

  • x: array (can be 1D or 2D) of x to evaluate z
  • y: array (can be 1D or 2D) of y to evaluate z
  • z: 2-D array of data to plot contour
  • cmap: color map (remember to import matplotlib.cm)
  • levels: contour levels
In [8]:
CS = plt.contourf(x, y, z, levels= np.linspace(-0.5,0.5,11),cmap=cm.rainbow)
plt.show()

plt.colorbar: add color bar to the figure

plt.colorbar(CS, orientation=...)

  • CS: plotting object
  • orientation: orientation of color bar on the figure 'horizontal' 'vertical'
In [9]:
CS = plt.contourf(x, y, z, levels= np.linspace(-0.5,0.5,11),cmap=cm.jet)
plt.colorbar(CS,orientation='vertical')
plt.show()

You can also overlay filled contour with contour lines:

In [15]:
CS = plt.contourf(x, y, z, levels=np.linspace(-0.5,0.5,11),cmap=cm.jet)
CS2 = plt.contour(x, y, z, levels=np.linspace(-0.5,0.5,11),colors='k')
plt.show()

plt.pcolormesh: fill grid with solid color (mosaic)

plt.pcolormesh(xx, yy, z, cmap=...,shading=...,edgecolors=...)

  • xx: 2D array of x mesh
  • yy: 2D array of y mesh
  • z: 2D array of data to be plotted
  • shading: blending 渲染
    • 'flat': no blending (default)
    • 'gouraud: blending
  • edgecolors: grid edge color (default is 'None')
In [11]:
CS = plt.pcolormesh(xx, yy, z, cmap=cm.jet,shading='flat')
plt.show()
In [12]:
CS = plt.pcolormesh(xx, yy, z, cmap=cm.jet,shading='flat',edgecolors='grey')
plt.show()
In [13]:
CS = plt.pcolormesh(xx, yy, z, cmap=cm.jet,shading='gouraud')
plt.show()

ax.plot_surface: plot the function on a 3D surface

Several steps are involved to show the function z(x,y) with 3D effects

  1. from mpl_toolkits.mplot3d import Axes3D
  2. generate a figure window object by plt.figure()
  3. set the projection to '3d by defining plotting object ax = fig.gca()
  4. plot the surface using ax.plot_surface (xx and yy has to be 2D mesh)
In [14]:
from mpl_toolkits.mplot3d import Axes3D

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

surf = ax.plot_surface(xx, yy, z, cmap=cm.jet)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title(r'z=exp(-sin(2x)$^2$-cos(2y)$^2$)-0.5')
plt.show()

Other 2D plot from Matplotlib library

  • Vectors on 2D coordinate: plt.quiver(x,y,u,v,color=...)
  • Streamlines: plt.streamplot(x,y,u,v,density=...,linewidth=...,color=...,cmap=...)
  • 2D histogram: plt.hist2d(x,y,bins=...,range=...)

Sample plots in Matplotlib

Here you’ll find a host of example plots with the code that generated them: http://matplotlib.org/tutorials/introductory/sample_plots.html#sphx-glr-tutorials-introductory-sample-plots-py