Python for Astronomy

Matplotlib

何勃亮
中国科学院国家天文台 中国虚拟天文台 (China-VO)
In [2]:
import matplotlib
import matplotlib.pyplot as plt
In [3]:
%%HTML
<iframe width=100% height=600 src="http://matplotlib.org/gallery.html" ></iframe>

概念

plt

import matplotlib.pyplot as plt

matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. In matplotlib.pyplot various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that “axes” here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).

  • Matplotlib 整个包
  • pyplot 集成了方便用户进行绘图的一系列指令
  • pylab 集成导入了pyplotnumpy在同一命名空间,但官方已经不推荐使用这个方式了。
In [4]:
x = np.linspace(0, 5, 10)
y = x ** 2

fig = plt.figure()

axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)

axes.plot(x, y, 'r')

axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');

Matplotlib 绘图步骤

  1. 建立图像(figure
  2. 添加一个画布空间(axes
  3. 画图(plot
  4. 修改绘图参数(label, title, etc

代码范式

1. 简单

import matplotlib.pyplot as plt
import numpy as np

x = ...
y = ...

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
plt.show()

定义绘图函数

def my_plotter(ax, data1, data2, param_dict):
    """
    A helper function to make a graph

    Parameters
    ----------
    ax : Axes
        The axes to draw to

    data1 : array
       The x data

    data2 : array
       The y data

    param_dict : dict
       Dictionary of kwargs to pass to ax.plot

    Returns
    -------
    out : list
        list of artists added
    """
    out = ax.plot(data1, data2, **param_dict)
    return out

调用模式 1

fig, ax = plt.subplots(1, 1)
my_plotter(ax, data1, data2, {'marker':'x'})

调用模式 2

fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, data1, data2, {'marker':'x'})
my_plotter(ax2, data3, data4, {'marker':'o'})
In [5]:
print(plt.style.available)
['ggplot', 'seaborn-bright', 'bmh', 'seaborn-darkgrid', 'seaborn-whitegrid', 'seaborn-dark', 'seaborn-white', 'seaborn-colorblind', 'fivethirtyeight', 'seaborn-notebook', 'classic', 'seaborn-pastel', 'dark_background', 'seaborn-deep', 'seaborn-muted', 'seaborn-poster', 'seaborn-talk', 'seaborn-paper', 'grayscale', 'seaborn-dark-palette', 'seaborn-ticks']
In [6]:
#plt.style.use('seaborn-paper')

x = np.linspace(0, 5, 10)
y = x ** 2

fig = plt.figure()

axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)

axes.plot(x, y, 'r')

axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
In [7]:
help(plt.plot)
Help on function plot in module matplotlib.pyplot:

plot(*args, **kwargs)
    Plot lines and/or markers to the
    :class:`~matplotlib.axes.Axes`.  *args* is a variable length
    argument, allowing for multiple *x*, *y* pairs with an
    optional format string.  For example, each of the following is
    legal::
    
        plot(x, y)        # plot x and y using default line style and color
        plot(x, y, 'bo')  # plot x and y using blue circle markers
        plot(y)           # plot y using x as index array 0..N-1
        plot(y, 'r+')     # ditto, but with red plusses
    
    If *x* and/or *y* is 2-dimensional, then the corresponding columns
    will be plotted.
    
    If used with labeled data, make sure that the color spec is not
    included as an element in data, as otherwise the last case
    ``plot("v","r", data={"v":..., "r":...)``
    can be interpreted as the first case which would do ``plot(v, r)``
    using the default line style and color.
    
    If not used with labeled data (i.e., without a data argument),
    an arbitrary number of *x*, *y*, *fmt* groups can be specified, as in::
    
        a.plot(x1, y1, 'g^', x2, y2, 'g-')
    
    Return value is a list of lines that were added.
    
    By default, each line is assigned a different style specified by a
    'style cycle'.  To change this behavior, you can edit the
    axes.prop_cycle rcParam.
    
    The following format string characters are accepted to control
    the line style or marker:
    
    ================    ===============================
    character           description
    ================    ===============================
    ``'-'``             solid line style
    ``'--'``            dashed line style
    ``'-.'``            dash-dot line style
    ``':'``             dotted line style
    ``'.'``             point marker
    ``','``             pixel marker
    ``'o'``             circle marker
    ``'v'``             triangle_down marker
    ``'^'``             triangle_up marker
    ``'<'``             triangle_left marker
    ``'>'``             triangle_right marker
    ``'1'``             tri_down marker
    ``'2'``             tri_up marker
    ``'3'``             tri_left marker
    ``'4'``             tri_right marker
    ``'s'``             square marker
    ``'p'``             pentagon marker
    ``'*'``             star marker
    ``'h'``             hexagon1 marker
    ``'H'``             hexagon2 marker
    ``'+'``             plus marker
    ``'x'``             x marker
    ``'D'``             diamond marker
    ``'d'``             thin_diamond marker
    ``'|'``             vline marker
    ``'_'``             hline marker
    ================    ===============================
    
    
    The following color abbreviations are supported:
    
    ==========  ========
    character   color
    ==========  ========
    'b'         blue
    'g'         green
    'r'         red
    'c'         cyan
    'm'         magenta
    'y'         yellow
    'k'         black
    'w'         white
    ==========  ========
    
    In addition, you can specify colors in many weird and
    wonderful ways, including full names (``'green'``), hex
    strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or
    grayscale intensities as a string (``'0.8'``).  Of these, the
    string specifications can be used in place of a ``fmt`` group,
    but the tuple forms can be used only as ``kwargs``.
    
    Line styles and colors are combined in a single format string, as in
    ``'bo'`` for blue circles.
    
    The *kwargs* can be used to set line properties (any property that has
    a ``set_*`` method).  You can use this to set a line label (for auto
    legends), linewidth, anitialising, marker face color, etc.  Here is an
    example::
    
        plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
        plot([1,2,3], [1,4,9], 'rs',  label='line 2')
        axis([0, 4, 0, 10])
        legend()
    
    If you make multiple lines with one plot command, the kwargs
    apply to all those lines, e.g.::
    
        plot(x1, y1, x2, y2, antialiased=False)
    
    Neither line will be antialiased.
    
    You do not need to use format strings, which are just
    abbreviations.  All of the line properties can be controlled
    by keyword arguments.  For example, you can set the color,
    marker, linestyle, and markercolor with::
    
        plot(x, y, color='green', linestyle='dashed', marker='o',
             markerfacecolor='blue', markersize=12).
    
    See :class:`~matplotlib.lines.Line2D` for details.
    
    The kwargs are :class:`~matplotlib.lines.Line2D` properties:
    
      agg_filter: unknown
      alpha: float (0.0 transparent through 1.0 opaque) 
      animated: [True | False] 
      antialiased or aa: [True | False] 
      axes: an :class:`~matplotlib.axes.Axes` instance 
      clip_box: a :class:`matplotlib.transforms.Bbox` instance 
      clip_on: [True | False] 
      clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] 
      color or c: any matplotlib color 
      contains: a callable function 
      dash_capstyle: ['butt' | 'round' | 'projecting'] 
      dash_joinstyle: ['miter' | 'round' | 'bevel'] 
      dashes: sequence of on/off ink in points 
      drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post'] 
      figure: a :class:`matplotlib.figure.Figure` instance 
      fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none'] 
      gid: an id string 
      label: string or anything printable with '%s' conversion. 
      linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
      linewidth or lw: float value in points 
      marker: :mod:`A valid marker style <matplotlib.markers>`
      markeredgecolor or mec: any matplotlib color 
      markeredgewidth or mew: float value in points 
      markerfacecolor or mfc: any matplotlib color 
      markerfacecoloralt or mfcalt: any matplotlib color 
      markersize or ms: float 
      markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
      path_effects: unknown
      picker: float distance in points or callable pick function ``fn(artist, event)`` 
      pickradius: float distance in points 
      rasterized: [True | False | None] 
      sketch_params: unknown
      snap: unknown
      solid_capstyle: ['butt' | 'round' |  'projecting'] 
      solid_joinstyle: ['miter' | 'round' | 'bevel'] 
      transform: a :class:`matplotlib.transforms.Transform` instance 
      url: a url string 
      visible: [True | False] 
      xdata: 1D array 
      ydata: 1D array 
      zorder: any number 
    
    kwargs *scalex* and *scaley*, if defined, are passed on to
    :meth:`~matplotlib.axes.Axes.autoscale_view` to determine
    whether the *x* and *y* axes are autoscaled; the default is
    *True*.
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All arguments with the following names: 'y', 'x'.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [8]:
fig = plt.figure()

axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes

# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')

# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');

图像尺寸,比例和分辨率

In [9]:
# 800 x 400, 100dpi

fig = plt.figure(figsize=(8,4), dpi=100)
<matplotlib.figure.Figure at 0x1020f9c18>
In [10]:
fig, ax = plt.subplots(figsize=(12,3))

ax.plot(x, y, 'r')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title');
In [11]:
# 保存图像

fig.savefig("filename.png")

fig.savefig("filename200.png", dpi=200)

图例,标题

In [12]:
ax.set_title("title");
In [13]:
ax.set_xlabel("x")
ax.set_ylabel("y");
In [14]:
ax.plot(x, x**2, label="curve1")
ax.plot(x, x**3, label="curve2")
ax.legend();
In [15]:
fig, ax = plt.subplots()

ax.plot(x, x**2, label="$y = x^2$")
ax.plot(x, x**3, label="$y = x^3$")
ax.legend(loc=2); # upper left corner
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title');
In [16]:
# Update the matplotlib configuration parameters:
matplotlib.rcParams.update({'font.size': 18, 'font.family': 'FZGuLi-S12S'})
In [17]:
fig, ax = plt.subplots()

ax.plot(x, x**2, label="$y = x^2$")
ax.plot(x, x**3, label="$y = x^3$")
ax.legend(loc=2); # upper left corner
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('标题');

颜色,线宽,线型

In [19]:
fig, ax = plt.subplots()

ax.plot(x, x+1, color="red", alpha=0.5) # half-transparant red
ax.plot(x, x+2, color="#1155dd")        # RGB hex code for a bluish color
ax.plot(x, x+3, color="#15cc55")        # RGB hex code for a greenish color
Out[19]:
[<matplotlib.lines.Line2D at 0x103c93f98>]
In [20]:
fig, ax = plt.subplots(figsize=(12,6))

ax.plot(x, x+1, color="blue", linewidth=0.25)
ax.plot(x, x+2, color="blue", linewidth=0.50)
ax.plot(x, x+3, color="blue", linewidth=1.00)
ax.plot(x, x+4, color="blue", linewidth=2.00)

# possible linestype options ‘-‘, ‘--’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="red", lw=2, linestyle='-')
ax.plot(x, x+6, color="red", lw=2, ls='-.')
ax.plot(x, x+7, color="red", lw=2, ls=':')

# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...

# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="green", lw=2, ls='--', marker='+')
ax.plot(x, x+10, color="green", lw=2, ls='--', marker='o')
ax.plot(x, x+11, color="green", lw=2, ls='--', marker='s')
ax.plot(x, x+12, color="green", lw=2, ls='--', marker='1')

# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8, 
        markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue");

坐标轴

In [21]:
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

axes[0].plot(x, x**2, x, x**3)
axes[0].set_title("default axes ranges")

axes[1].plot(x, x**2, x, x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")

axes[2].plot(x, x**2, x, x**3)
axes[2].set_ylim([0, 60])
axes[2].set_xlim([2, 5])
axes[2].set_title("custom axes range");
In [22]:
## Logarithmic scale

fig, axes = plt.subplots(1, 2, figsize=(10,4))
      
axes[0].plot(x, x**2, x, np.exp(x))
axes[0].set_title("Normal scale")

axes[1].plot(x, x**2, x, np.exp(x))
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)");
In [23]:
# 定制刻度显示

fig, ax = plt.subplots(figsize=(10, 4))

ax.plot(x, x**2, x, x**3, lw=2)

ax.set_xticks([1, 2, 3, 4, 5])
ax.set_xticklabels([r'$\alpha$', r'$\beta$', r'$\gamma$', r'$\delta$', r'$\epsilon$'], fontsize=18)

yticks = [0, 50, 100, 150]
ax.set_yticks(yticks)
ax.set_yticklabels(["$%.1f$" % y for y in yticks], fontsize=18); # use LaTeX formatted labels
In [24]:
# 科学记数法

fig, ax = plt.subplots(1, 1)
      
ax.plot(x, x**2, x, np.exp(x))
ax.set_title("scientific notation")

ax.set_yticks([0, 50, 100, 150])

from matplotlib import ticker
formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True) 
formatter.set_powerlimits((-1,1)) 
ax.yaxis.set_major_formatter(formatter) 
In [25]:
# distance between x and y axis and the numbers on the axes
matplotlib.rcParams['xtick.major.pad'] = 15
matplotlib.rcParams['ytick.major.pad'] = 15

fig, ax = plt.subplots(1, 1)
      
ax.plot(x, x**2, x, np.exp(x))
ax.set_yticks([0, 50, 100, 150])

ax.set_title("label and axis spacing")

# padding between axis label and axis numbers
ax.xaxis.labelpad = 15
ax.yaxis.labelpad = 15

ax.set_xlabel("x")
ax.set_ylabel("y");
In [27]:
# Axis position adjustments

fig, ax = plt.subplots(1, 1)
      
ax.plot(x, x**2, x, np.exp(x))
ax.set_yticks([0, 50, 100, 150])

ax.set_title("title")
ax.set_xlabel("x")
ax.set_ylabel("y")

fig.subplots_adjust(left=0.15, right=.9, bottom=0.1, top=0.9);

网格

In [28]:
fig, axes = plt.subplots(1, 2, figsize=(10,3))

# default grid appearance
axes[0].plot(x, x**2, x, x**3, lw=2)
axes[0].grid(True)

# custom grid appearance
axes[1].plot(x, x**2, x, x**3, lw=2)
axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)

坐标轴颜色

In [29]:
fig, ax = plt.subplots(figsize=(6,2))

ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('blue')

ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)

# turn off axis spine to the right
ax.spines['right'].set_color("none")
ax.yaxis.tick_left() # only ticks on the left side

双坐标轴

In [30]:
fig, ax1 = plt.subplots()

ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
    label.set_color("blue")
    
ax2 = ax1.twinx()
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in ax2.get_yticklabels():
    label.set_color("red")

去掉边框

In [31]:
fig, ax = plt.subplots()

ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0)) # set position of x spine to x=0

ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))   # set position of y spine to y=0

xx = np.linspace(-0.75, 1., 100)
ax.plot(xx, xx**3);

散点图等

In [32]:
help(plt.scatter)
Help on function scatter in module matplotlib.pyplot:

scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)
    Make a scatter plot of x vs y, where x and y are sequence like objects
    of the same lengths.
    
    Parameters
    ----------
    x, y : array_like, shape (n, )
        Input data
    
    s : scalar or array_like, shape (n, ), optional, default: 20
        size in points^2.
    
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs
        (see below). Note that `c` should not be a single numeric RGB or
        RGBA sequence because that is indistinguishable from an array of
        values to be colormapped.  `c` can be a 2-D array in which the
        rows are RGB or RGBA, however, including the case of a single
        row to specify the same color for all points.
    
    marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o'
        See `~matplotlib.markers` for more information on the different
        styles of markers scatter supports. `marker` can be either
        an instance of the class or the text shorthand for a particular
        marker.
    
    cmap : `~matplotlib.colors.Colormap`, optional, default: None
        A `~matplotlib.colors.Colormap` instance or registered name.
        `cmap` is only used if `c` is an array of floats. If None,
        defaults to rc `image.cmap`.
    
    norm : `~matplotlib.colors.Normalize`, optional, default: None
        A `~matplotlib.colors.Normalize` instance is used to scale
        luminance data to 0, 1. `norm` is only used if `c` is an array of
        floats. If `None`, use the default :func:`normalize`.
    
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.  Note if you pass a `norm` instance, your
        settings for `vmin` and `vmax` will be ignored.
    
    alpha : scalar, optional, default: None
        The alpha blending value, between 0 (transparent) and 1 (opaque)
    
    linewidths : scalar or array_like, optional, default: None
        If None, defaults to (lines.linewidth,).
    
    edgecolors : color or sequence of color, optional, default: None
        If None, defaults to (patch.edgecolor).
        If 'face', the edge color will always be the same as
        the face color.  If it is 'none', the patch boundary will not
        be drawn.  For non-filled markers, the `edgecolors` kwarg
        is ignored; color is determined by `c`.
    
    Returns
    -------
    paths : `~matplotlib.collections.PathCollection`
    
    Other parameters
    ----------------
    kwargs : `~matplotlib.collections.Collection` properties
    
    Notes
    ------
    Any or all of `x`, `y`, `s`, and `c` may be masked arrays, in
    which case all masks will be combined and only unmasked points
    will be plotted.
    
    Fundamentally, scatter works with 1-D arrays; `x`, `y`, `s`,
    and `c` may be input as 2-D arrays, but within scatter
    they will be flattened. The exception is `c`, which
    will be flattened only if its size matches the size of `x`
    and `y`.
    
    Examples
    --------
    .. plot:: mpl_examples/shapes_and_collections/scatter_demo.py
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All arguments with the following names: 'linewidths', 'y', 'edgecolors', 'facecolor', 's', 'facecolors', 'c', 'x', 'color'.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [33]:
help(plt.step)
Help on function step in module matplotlib.pyplot:

step(x, y, *args, **kwargs)
    Make a step plot.
    
    Call signature::
    
      step(x, y, *args, **kwargs)
    
    Additional keyword args to :func:`step` are the same as those
    for :func:`~matplotlib.pyplot.plot`.
    
    *x* and *y* must be 1-D sequences, and it is assumed, but not checked,
    that *x* is uniformly increasing.
    
    Keyword arguments:
    
    *where*: [ 'pre' | 'post' | 'mid'  ]
      If 'pre' (the default), the interval from x[i] to x[i+1] has level
      y[i+1].
    
      If 'post', that interval has level y[i].
    
      If 'mid', the jumps in *y* occur half-way between the
      *x*-values.
    
    Return value is a list of lines that were added.
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All arguments with the following names: 'y', 'x'.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [34]:
help(plt.bar)
Help on function bar in module matplotlib.pyplot:

bar(left, height, width=0.8, bottom=None, hold=None, data=None, **kwargs)
    Make a bar plot.
    
    Make a bar plot with rectangles bounded by:
    
      `left`, `left` + `width`, `bottom`, `bottom` + `height`
            (left, right, bottom and top edges)
    
    Parameters
    ----------
    left : sequence of scalars
        the x coordinates of the left sides of the bars
    
    height : sequence of scalars
        the heights of the bars
    
    width : scalar or array-like, optional
        the width(s) of the bars
        default: 0.8
    
    bottom : scalar or array-like, optional
        the y coordinate(s) of the bars
        default: None
    
    color : scalar or array-like, optional
        the colors of the bar faces
    
    edgecolor : scalar or array-like, optional
        the colors of the bar edges
    
    linewidth : scalar or array-like, optional
        width of bar edge(s). If None, use default
        linewidth; If 0, don't draw edges.
        default: None
    
    tick_label : string or array-like, optional
        the tick labels of the bars
        default: None
    
    xerr : scalar or array-like, optional
        if not None, will be used to generate errorbar(s) on the bar chart
        default: None
    
    yerr : scalar or array-like, optional
        if not None, will be used to generate errorbar(s) on the bar chart
        default: None
    
    ecolor : scalar or array-like, optional
        specifies the color of errorbar(s)
        default: None
    
    capsize : scalar, optional
       determines the length in points of the error bar caps
       default: None, which will take the value from the
       ``errorbar.capsize`` :data:`rcParam<matplotlib.rcParams>`.
    
    error_kw : dict, optional
        dictionary of kwargs to be passed to errorbar method. *ecolor* and
        *capsize* may be specified here rather than as independent kwargs.
    
    align : {'edge',  'center'}, optional
        If 'edge', aligns bars by their left edges (for vertical bars) and
        by their bottom edges (for horizontal bars). If 'center', interpret
        the `left` argument as the coordinates of the centers of the bars.
        To align on the align bars on the right edge pass a negative
        `width`.
    
    orientation : {'vertical',  'horizontal'}, optional
        The orientation of the bars.
    
    log : boolean, optional
        If true, sets the axis to be log scale.
        default: False
    
    Returns
    -------
    bars : matplotlib.container.BarContainer
        Container with all of the bars + errorbars
    
    Notes
    -----
    The optional arguments `color`, `edgecolor`, `linewidth`,
    `xerr`, and `yerr` can be either scalars or sequences of
    length equal to the number of bars.  This enables you to use
    bar as the basis for stacked bar charts, or candlestick plots.
    Detail: `xerr` and `yerr` are passed directly to
    :meth:`errorbar`, so they can also have shape 2xN for
    independent specification of lower and upper errors.
    
    Other optional kwargs:
    
      agg_filter: unknown
      alpha: float or None 
      animated: [True | False] 
      antialiased or aa: [True | False]  or None for default 
      axes: an :class:`~matplotlib.axes.Axes` instance 
      capstyle: ['butt' | 'round' | 'projecting'] 
      clip_box: a :class:`matplotlib.transforms.Bbox` instance 
      clip_on: [True | False] 
      clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] 
      color: matplotlib color spec
      contains: a callable function 
      edgecolor or ec: mpl color spec, or None for default, or 'none' for no color 
      facecolor or fc: mpl color spec, or None for default, or 'none' for no color 
      figure: a :class:`matplotlib.figure.Figure` instance 
      fill: [True | False] 
      gid: an id string 
      hatch: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*'] 
      joinstyle: ['miter' | 'round' | 'bevel'] 
      label: string or anything printable with '%s' conversion. 
      linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
      linewidth or lw: float or None for default 
      path_effects: unknown
      picker: [None|float|boolean|callable] 
      rasterized: [True | False | None] 
      sketch_params: unknown
      snap: unknown
      transform: :class:`~matplotlib.transforms.Transform` instance 
      url: a url string 
      visible: [True | False] 
      zorder: any number 
    
    See also
    --------
    barh: Plot a horizontal bar plot.
    
    Examples
    --------
    
    **Example:** A stacked bar chart.
    
    .. plot:: mpl_examples/pylab_examples/bar_stacked.py
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All arguments with the following names: 'height', 'linewidth', 'tick_label', 'left', 'width', 'xerr', 'ecolor', 'bottom', 'yerr', 'edgecolor', 'color'.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [35]:
help(plt.fill_between)
Help on function fill_between in module matplotlib.pyplot:

fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, hold=None, data=None, **kwargs)
    Make filled polygons between two curves.
    
    
    Create a :class:`~matplotlib.collections.PolyCollection`
    filling the regions between *y1* and *y2* where
    ``where==True``
    
    Parameters
    ----------
    x : array
        An N-length array of the x data
    
    y1 : array
        An N-length array (or scalar) of the y data
    
    y2 : array
        An N-length array (or scalar) of the y data
    
    where : array, optional
        If `None`, default to fill between everywhere.  If not `None`,
        it is an N-length numpy boolean array and the fill will
        only happen over the regions where ``where==True``.
    
    interpolate : bool, optional
        If `True`, interpolate between the two lines to find the
        precise point of intersection.  Otherwise, the start and
        end points of the filled region will only occur on explicit
        values in the *x* array.
    
    step : {'pre', 'post', 'mid'}, optional
        If not None, fill with step logic.
    
    
    Notes
    -----
    
    Additional Keyword args passed on to the
    :class:`~matplotlib.collections.PolyCollection`.
    
    kwargs control the :class:`~matplotlib.patches.Polygon` properties:
    
      agg_filter: unknown
      alpha: float or None 
      animated: [True | False] 
      antialiased or antialiaseds: Boolean or sequence of booleans 
      array: unknown
      axes: an :class:`~matplotlib.axes.Axes` instance 
      clim: a length 2 sequence of floats 
      clip_box: a :class:`matplotlib.transforms.Bbox` instance 
      clip_on: [True | False] 
      clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] 
      cmap: a colormap or registered colormap name 
      color: matplotlib color arg or sequence of rgba tuples
      contains: a callable function 
      edgecolor or edgecolors: matplotlib color spec or sequence of specs 
      facecolor or facecolors: matplotlib color spec or sequence of specs 
      figure: a :class:`matplotlib.figure.Figure` instance 
      gid: an id string 
      hatch: [ '/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] 
      label: string or anything printable with '%s' conversion. 
      linestyle or dashes or linestyles: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
      linewidth or linewidths or lw: float or sequence of floats 
      norm: unknown
      offset_position: unknown
      offsets: float or sequence of floats 
      path_effects: unknown
      picker: [None|float|boolean|callable] 
      pickradius: unknown
      rasterized: [True | False | None] 
      sketch_params: unknown
      snap: unknown
      transform: :class:`~matplotlib.transforms.Transform` instance 
      url: a url string 
      urls: unknown
      visible: [True | False] 
      zorder: any number 
    
    Examples
    --------
    
    .. plot:: mpl_examples/pylab_examples/fill_between_demo.py
    
    See Also
    --------
    
        :meth:`fill_betweenx`
            for filling between two sets of x-values
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All arguments with the following names: 'where', 'y1', 'y2', 'x'.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [36]:
n = np.array([0,1,2,3,4,5])

fig, axes = plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx)))
axes[0].set_title("scatter")

axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
axes[3].set_title("fill_between");
In [37]:
## Scatter 
fig, ax = plt.subplots(1, 1)
      
x = np.random.rand(200)
y = np.random.rand(200)

size = np.random.rand(200)*30
color = np.random.rand(200)

im = ax.scatter(x, y, size, color)
fig.colorbar(im,ax=ax)
Out[37]:
<matplotlib.colorbar.Colorbar at 0x1051a57f0>

极坐标

In [38]:
# polar plot using add_axes and polar projection
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = np.linspace(0, 2 * np.pi, 100)
ax.plot(t, t, color='blue', lw=3);

直方图

In [39]:
help(plt.hist)
Help on function hist in module matplotlib.pyplot:

hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)
    Plot a histogram.
    
    Compute and draw the histogram of *x*. The return value is a
    tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
    [*patches0*, *patches1*,...]) if the input contains multiple
    data.
    
    Multiple data can be provided via *x* as a list of datasets
    of potentially different length ([*x0*, *x1*, ...]), or as
    a 2-D ndarray in which each column is a dataset.  Note that
    the ndarray form is transposed relative to the list form.
    
    Masked arrays are not supported at present.
    
    Parameters
    ----------
    x : (n,) array or sequence of (n,) arrays
        Input values, this takes either a single array or a sequency of
        arrays which are not required to be of the same length
    
    bins : integer or array_like, optional
        If an integer is given, `bins + 1` bin edges are returned,
        consistently with :func:`numpy.histogram` for numpy version >=
        1.3.
    
        Unequally spaced bins are supported if `bins` is a sequence.
    
        default is 10
    
    range : tuple or None, optional
        The lower and upper range of the bins. Lower and upper outliers
        are ignored. If not provided, `range` is (x.min(), x.max()). Range
        has no effect if `bins` is a sequence.
    
        If `bins` is a sequence or `range` is specified, autoscaling
        is based on the specified bin range instead of the
        range of x.
    
        Default is ``None``
    
    normed : boolean, optional
        If `True`, the first element of the return tuple will
        be the counts normalized to form a probability density, i.e.,
        ``n/(len(x)`dbin)``, i.e., the integral of the histogram will sum
        to 1. If *stacked* is also *True*, the sum of the histograms is
        normalized to 1.
    
        Default is ``False``
    
    weights : (n, ) array_like or None, optional
        An array of weights, of the same shape as `x`.  Each value in `x`
        only contributes its associated weight towards the bin count
        (instead of 1).  If `normed` is True, the weights are normalized,
        so that the integral of the density over the range remains 1.
    
        Default is ``None``
    
    cumulative : boolean, optional
        If `True`, then a histogram is computed where each bin gives the
        counts in that bin plus all bins for smaller values. The last bin
        gives the total number of datapoints.  If `normed` is also `True`
        then the histogram is normalized such that the last bin equals 1.
        If `cumulative` evaluates to less than 0 (e.g., -1), the direction
        of accumulation is reversed.  In this case, if `normed` is also
        `True`, then the histogram is normalized such that the first bin
        equals 1.
    
        Default is ``False``
    
    bottom : array_like, scalar, or None
        Location of the bottom baseline of each bin.  If a scalar,
        the base line for each bin is shifted by the same amount.
        If an array, each bin is shifted independently and the length
        of bottom must match the number of bins.  If None, defaults to 0.
    
        Default is ``None``
    
    histtype : {'bar', 'barstacked', 'step',  'stepfilled'}, optional
        The type of histogram to draw.
    
        - 'bar' is a traditional bar-type histogram.  If multiple data
          are given the bars are aranged side by side.
    
        - 'barstacked' is a bar-type histogram where multiple
          data are stacked on top of each other.
    
        - 'step' generates a lineplot that is by default
          unfilled.
    
        - 'stepfilled' generates a lineplot that is by default
          filled.
    
        Default is 'bar'
    
    align : {'left', 'mid', 'right'}, optional
        Controls how the histogram is plotted.
    
            - 'left': bars are centered on the left bin edges.
    
            - 'mid': bars are centered between the bin edges.
    
            - 'right': bars are centered on the right bin edges.
    
        Default is 'mid'
    
    orientation : {'horizontal', 'vertical'}, optional
        If 'horizontal', `~matplotlib.pyplot.barh` will be used for
        bar-type histograms and the *bottom* kwarg will be the left edges.
    
    rwidth : scalar or None, optional
        The relative width of the bars as a fraction of the bin width.  If
        `None`, automatically compute the width.
    
        Ignored if `histtype` is 'step' or 'stepfilled'.
    
        Default is ``None``
    
    log : boolean, optional
        If `True`, the histogram axis will be set to a log scale. If `log`
        is `True` and `x` is a 1D array, empty bins will be filtered out
        and only the non-empty (`n`, `bins`, `patches`) will be returned.
    
        Default is ``False``
    
    color : color or array_like of colors or None, optional
        Color spec or sequence of color specs, one per dataset.  Default
        (`None`) uses the standard line color sequence.
    
        Default is ``None``
    
    label : string or None, optional
        String, or sequence of strings to match multiple datasets.  Bar
        charts yield multiple patches per dataset, but only the first gets
        the label, so that the legend command will work as expected.
    
        default is ``None``
    
    stacked : boolean, optional
        If `True`, multiple data are stacked on top of each other If
        `False` multiple data are aranged side by side if histtype is
        'bar' or on top of each other if histtype is 'step'
    
        Default is ``False``
    
    Returns
    -------
    n : array or list of arrays
        The values of the histogram bins. See **normed** and **weights**
        for a description of the possible semantics. If input **x** is an
        array, then this is an array of length **nbins**. If input is a
        sequence arrays ``[data1, data2,..]``, then this is a list of
        arrays with the values of the histograms for each of the arrays
        in the same order.
    
    bins : array
        The edges of the bins. Length nbins + 1 (nbins left edges and right
        edge of last bin).  Always a single array even when multiple data
        sets are passed in.
    
    patches : list or list of lists
        Silent list of individual patches used to create the histogram
        or list of such list if multiple input datasets.
    
    Other Parameters
    ----------------
    kwargs : `~matplotlib.patches.Patch` properties
    
    See also
    --------
    hist2d : 2D histograms
    
    Notes
    -----
    Until numpy release 1.5, the underlying numpy histogram function was
    incorrect with `normed`=`True` if bin sizes were unequal.  MPL
    inherited that error.  It is now corrected within MPL when using
    earlier numpy versions.
    
    Examples
    --------
    .. plot:: mpl_examples/statistics/histogram_demo_features.py
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All arguments with the following names: 'weights', 'x'.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [62]:
n = np.random.randn(100000)
fig, axes = plt.subplots(1, 2, figsize=(12,4))

axes[0].hist(n, bins=50)
axes[0].set_title("Default histogram")
axes[0].set_xlim((min(n), max(n)))

axes[1].hist(n, cumulative=True, bins=50)
axes[1].set_title("Cumulative detailed histogram")
axes[1].set_xlim((min(n), max(n)));

文字标注

In [41]:
fig, ax = plt.subplots()

ax.plot(xx, xx**2, xx, xx**3)

ax.text(0.15, 0.2, r"$y=x^2$", fontsize=20, color="blue")
ax.text(0.65, 0.1, r"$y=x^3$", fontsize=20, color="green");

多图模式

  • subplot
  • subplot2grid
  • gridspec
  • add_axes

subplot

In [42]:
help(plt.subplots)
Help on function subplots in module matplotlib.pyplot:

subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
    Create a figure with a set of subplots already made.
    
    This utility wrapper makes it convenient to create common layouts of
    subplots, including the enclosing figure object, in a single call.
    
    Keyword arguments:
    
      *nrows* : int
        Number of rows of the subplot grid.  Defaults to 1.
    
      *ncols* : int
        Number of columns of the subplot grid.  Defaults to 1.
    
      *sharex* : string or bool
        If *True*, the X axis will be shared amongst all subplots.  If
        *True* and you have multiple rows, the x tick labels on all but
        the last row of plots will have visible set to *False*
        If a string must be one of "row", "col", "all", or "none".
        "all" has the same effect as *True*, "none" has the same effect
        as *False*.
        If "row", each subplot row will share a X axis.
        If "col", each subplot column will share a X axis and the x tick
        labels on all but the last row will have visible set to *False*.
    
      *sharey* : string or bool
        If *True*, the Y axis will be shared amongst all subplots. If
        *True* and you have multiple columns, the y tick labels on all but
        the first column of plots will have visible set to *False*
        If a string must be one of "row", "col", "all", or "none".
        "all" has the same effect as *True*, "none" has the same effect
        as *False*.
        If "row", each subplot row will share a Y axis and the y tick
        labels on all but the first column will have visible set to *False*.
        If "col", each subplot column will share a Y axis.
    
      *squeeze* : bool
        If *True*, extra dimensions are squeezed out from the
        returned axis object:
    
        - if only one subplot is constructed (nrows=ncols=1), the
          resulting single Axis object is returned as a scalar.
    
        - for Nx1 or 1xN subplots, the returned object is a 1-d numpy
          object array of Axis objects are returned as numpy 1-d
          arrays.
    
        - for NxM subplots with N>1 and M>1 are returned as a 2d
          array.
    
        If *False*, no squeezing at all is done: the returned axis
        object is always a 2-d array containing Axis instances, even if it
        ends up being 1x1.
    
      *subplot_kw* : dict
        Dict with keywords passed to the
        :meth:`~matplotlib.figure.Figure.add_subplot` call used to
        create each subplots.
    
      *gridspec_kw* : dict
        Dict with keywords passed to the
        :class:`~matplotlib.gridspec.GridSpec` constructor used to create
        the grid the subplots are placed on.
    
      *fig_kw* : dict
        Dict with keywords passed to the :func:`figure` call.  Note that all
        keywords not recognized above will be automatically included here.
    
    Returns:
    
    fig, ax : tuple
    
      - *fig* is the :class:`matplotlib.figure.Figure` object
    
      - *ax* can be either a single axis object or an array of axis
        objects if more than one subplot was created.  The dimensions
        of the resulting array can be controlled with the squeeze
        keyword, see above.
    
    Examples::
    
        x = np.linspace(0, 2*np.pi, 400)
        y = np.sin(x**2)
    
        # Just a figure and one subplot
        f, ax = plt.subplots()
        ax.plot(x, y)
        ax.set_title('Simple plot')
    
        # Two subplots, unpack the output array immediately
        f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
        ax1.plot(x, y)
        ax1.set_title('Sharing Y axis')
        ax2.scatter(x, y)
    
        # Four polar axes
        plt.subplots(2, 2, subplot_kw=dict(polar=True))
    
        # Share a X axis with each column of subplots
        plt.subplots(2, 2, sharex='col')
    
        # Share a Y axis with each row of subplots
        plt.subplots(2, 2, sharey='row')
    
        # Share a X and Y axis with all subplots
        plt.subplots(2, 2, sharex='all', sharey='all')
        # same as
        plt.subplots(2, 2, sharex=True, sharey=True)

In [43]:
fig, ax = plt.subplots(2, 3)
fig.tight_layout()

subplot2grid

In [44]:
fig = plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2,0))
ax5 = plt.subplot2grid((3,3), (2,1))
fig.tight_layout()

gridspec

In [45]:
import matplotlib.gridspec as gridspec
In [46]:
fig = plt.figure()

gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
    ax = fig.add_subplot(g)
    
fig.tight_layout()

gridspec

In [47]:
fig, ax = plt.subplots()

ax.plot(xx, xx**2, xx, xx**3)
fig.tight_layout()

# inset
inset_ax = fig.add_axes([0.2, 0.55, 0.35, 0.35]) # X, Y, width, height

inset_ax.plot(xx, xx**2, xx, xx**3)
inset_ax.set_title('zoom near origin')

# set axis range
inset_ax.set_xlim(-.2, .2)
inset_ax.set_ylim(-.005, .01)

# set axis tick locations
inset_ax.set_yticks([0, 0.005, 0.01])
inset_ax.set_xticks([-0.1,0,.1]);
In [48]:
alpha = 0.7
phi_ext = 2 * np.pi * 0.5

def flux_qubit_potential(phi_m, phi_p):
    return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext - 2*phi_p)
In [49]:
phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T

pcolor

In [50]:
help(plt.pcolor)
Help on function pcolor in module matplotlib.pyplot:

pcolor(*args, **kwargs)
    Create a pseudocolor plot of a 2-D array.
    
    .. note::
    
        pcolor can be very slow for large arrays; consider
        using the similar but much faster
        :func:`~matplotlib.pyplot.pcolormesh` instead.
    
    Call signatures::
    
      pcolor(C, **kwargs)
      pcolor(X, Y, C, **kwargs)
    
    *C* is the array of color values.
    
    *X* and *Y*, if given, specify the (*x*, *y*) coordinates of
    the colored quadrilaterals; the quadrilateral for C[i,j] has
    corners at::
    
      (X[i,   j],   Y[i,   j]),
      (X[i,   j+1], Y[i,   j+1]),
      (X[i+1, j],   Y[i+1, j]),
      (X[i+1, j+1], Y[i+1, j+1]).
    
    Ideally the dimensions of *X* and *Y* should be one greater
    than those of *C*; if the dimensions are the same, then the
    last row and column of *C* will be ignored.
    
    Note that the column index corresponds to the
    *x*-coordinate, and the row index corresponds to *y*; for
    details, see the :ref:`Grid Orientation
    <axes-pcolor-grid-orientation>` section below.
    
    If either or both of *X* and *Y* are 1-D arrays or column vectors,
    they will be expanded as needed into the appropriate 2-D arrays,
    making a rectangular grid.
    
    *X*, *Y* and *C* may be masked arrays.  If either C[i, j], or one
    of the vertices surrounding C[i,j] (*X* or *Y* at [i, j], [i+1, j],
    [i, j+1],[i+1, j+1]) is masked, nothing is plotted.
    
    Keyword arguments:
    
      *cmap*: [ *None* | Colormap ]
        A :class:`matplotlib.colors.Colormap` instance. If *None*, use
        rc settings.
    
      *norm*: [ *None* | Normalize ]
        An :class:`matplotlib.colors.Normalize` instance is used
        to scale luminance data to 0,1. If *None*, defaults to
        :func:`normalize`.
    
      *vmin*/*vmax*: [ *None* | scalar ]
        *vmin* and *vmax* are used in conjunction with *norm* to
        normalize luminance data.  If either is *None*, it
        is autoscaled to the respective min or max
        of the color array *C*.  If not *None*, *vmin* or
        *vmax* passed in here override any pre-existing values
        supplied in the *norm* instance.
    
      *shading*: [ 'flat' | 'faceted' ]
        If 'faceted', a black grid is drawn around each rectangle; if
        'flat', edges are not drawn. Default is 'flat', contrary to
        MATLAB.
    
        This kwarg is deprecated; please use 'edgecolors' instead:
          * shading='flat' -- edgecolors='none'
          * shading='faceted  -- edgecolors='k'
    
      *edgecolors*: [ *None* | ``'none'`` | color | color sequence]
        If *None*, the rc setting is used by default.
    
        If ``'none'``, edges will not be visible.
    
        An mpl color or sequence of colors will set the edge color
    
      *alpha*: ``0 <= scalar <= 1``   or *None*
        the alpha blending value
    
      *snap*: bool
        Whether to snap the mesh to pixel boundaries.
    
    Return value is a :class:`matplotlib.collections.Collection`
    instance.
    
    .. _axes-pcolor-grid-orientation:
    
    The grid orientation follows the MATLAB convention: an
    array *C* with shape (*nrows*, *ncolumns*) is plotted with
    the column number as *X* and the row number as *Y*, increasing
    up; hence it is plotted the way the array would be printed,
    except that the *Y* axis is reversed.  That is, *C* is taken
    as *C*(*y*, *x*).
    
    Similarly for :func:`meshgrid`::
    
      x = np.arange(5)
      y = np.arange(3)
      X, Y = np.meshgrid(x, y)
    
    is equivalent to::
    
      X = array([[0, 1, 2, 3, 4],
                 [0, 1, 2, 3, 4],
                 [0, 1, 2, 3, 4]])
    
      Y = array([[0, 0, 0, 0, 0],
                 [1, 1, 1, 1, 1],
                 [2, 2, 2, 2, 2]])
    
    so if you have::
    
      C = rand(len(x), len(y))
    
    then you need to transpose C::
    
      pcolor(X, Y, C.T)
    
    or::
    
      pcolor(C.T)
    
    MATLAB :func:`pcolor` always discards the last row and column
    of *C*, but matplotlib displays the last row and column if *X* and
    *Y* are not specified, or if *X* and *Y* have one more row and
    column than *C*.
    
    kwargs can be used to control the
    :class:`~matplotlib.collections.PolyCollection` properties:
    
      agg_filter: unknown
      alpha: float or None 
      animated: [True | False] 
      antialiased or antialiaseds: Boolean or sequence of booleans 
      array: unknown
      axes: an :class:`~matplotlib.axes.Axes` instance 
      clim: a length 2 sequence of floats 
      clip_box: a :class:`matplotlib.transforms.Bbox` instance 
      clip_on: [True | False] 
      clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] 
      cmap: a colormap or registered colormap name 
      color: matplotlib color arg or sequence of rgba tuples
      contains: a callable function 
      edgecolor or edgecolors: matplotlib color spec or sequence of specs 
      facecolor or facecolors: matplotlib color spec or sequence of specs 
      figure: a :class:`matplotlib.figure.Figure` instance 
      gid: an id string 
      hatch: [ '/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*' ] 
      label: string or anything printable with '%s' conversion. 
      linestyle or dashes or linestyles: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
      linewidth or linewidths or lw: float or sequence of floats 
      norm: unknown
      offset_position: unknown
      offsets: float or sequence of floats 
      path_effects: unknown
      picker: [None|float|boolean|callable] 
      pickradius: unknown
      rasterized: [True | False | None] 
      sketch_params: unknown
      snap: unknown
      transform: :class:`~matplotlib.transforms.Transform` instance 
      url: a url string 
      urls: unknown
      visible: [True | False] 
      zorder: any number 
    
    .. note::
    
        The default *antialiaseds* is False if the default
        *edgecolors*="none" is used.  This eliminates artificial lines
        at patch boundaries, and works regardless of the value of
        alpha.  If *edgecolors* is not "none", then the default
        *antialiaseds* is taken from
        rcParams['patch.antialiased'], which defaults to *True*.
        Stroking the edges may be preferred if *alpha* is 1, but
        will cause artifacts otherwise.
    
    .. seealso::
    
        :func:`~matplotlib.pyplot.pcolormesh`
            For an explanation of the differences between
            pcolor and pcolormesh.
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All positional and all keyword arguments.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [51]:
fig, ax = plt.subplots()

p = ax.pcolor(X/(2*np.pi), Y/(2*np.pi), Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max())
cb = fig.colorbar(p, ax=ax)

imshow

In [52]:
help(plt.imshow)
Help on function imshow in module matplotlib.pyplot:

imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
    Display an image on the axes.
    
    Parameters
    -----------
    X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
        Display the image in `X` to current axes.  `X` may be a float
        array, a uint8 array or a PIL image. If `X` is an array, it
        can have the following shapes:
    
        - MxN -- luminance (grayscale, float array only)
        - MxNx3 -- RGB (float or uint8 array)
        - MxNx4 -- RGBA (float or uint8 array)
    
        The value for each component of MxNx3 and MxNx4 float arrays
        should be in the range 0.0 to 1.0; MxN float arrays may be
        normalised.
    
    cmap : `~matplotlib.colors.Colormap`, optional, default: None
        If None, default to rc `image.cmap` value. `cmap` is ignored when
        `X` has RGB(A) information
    
    aspect : ['auto' | 'equal' | scalar], optional, default: None
        If 'auto', changes the image aspect ratio to match that of the
        axes.
    
        If 'equal', and `extent` is None, changes the axes aspect ratio to
        match that of the image. If `extent` is not `None`, the axes
        aspect ratio is changed to match that of the extent.
    
        If None, default to rc ``image.aspect`` value.
    
    interpolation : string, optional, default: None
        Acceptable values are 'none', 'nearest', 'bilinear', 'bicubic',
        'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
        'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc',
        'lanczos'
    
        If `interpolation` is None, default to rc `image.interpolation`.
        See also the `filternorm` and `filterrad` parameters.
        If `interpolation` is 'none', then no interpolation is performed
        on the Agg, ps and pdf backends. Other backends will fall back to
        'nearest'.
    
    norm : `~matplotlib.colors.Normalize`, optional, default: None
        A `~matplotlib.colors.Normalize` instance is used to scale
        luminance data to 0, 1. If `None`, use the default
        func:`normalize`. `norm` is only used if `X` is an array of
        floats.
    
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with norm to normalize
        luminance data.  Note if you pass a `norm` instance, your
        settings for `vmin` and `vmax` will be ignored.
    
    alpha : scalar, optional, default: None
        The alpha blending value, between 0 (transparent) and 1 (opaque)
    
    origin : ['upper' | 'lower'], optional, default: None
        Place the [0,0] index of the array in the upper left or lower left
        corner of the axes. If None, default to rc `image.origin`.
    
    extent : scalars (left, right, bottom, top), optional, default: None
        The location, in data-coordinates, of the lower-left and
        upper-right corners. If `None`, the image is positioned such that
        the pixel centers fall on zero-based (row, column) indices.
    
    shape : scalars (columns, rows), optional, default: None
        For raw buffer images
    
    filternorm : scalar, optional, default: 1
        A parameter for the antigrain image resize filter.  From the
        antigrain documentation, if `filternorm` = 1, the filter
        normalizes integer values and corrects the rounding errors. It
        doesn't do anything with the source floating point values, it
        corrects only integers according to the rule of 1.0 which means
        that any sum of pixel weights must be equal to 1.0.  So, the
        filter function must produce a graph of the proper shape.
    
    filterrad : scalar, optional, default: 4.0
        The filter radius for filters that have a radius parameter, i.e.
        when interpolation is one of: 'sinc', 'lanczos' or 'blackman'
    
    Returns
    --------
    image : `~matplotlib.image.AxesImage`
    
    Other parameters
    ----------------
    kwargs : `~matplotlib.artist.Artist` properties.
    
    See also
    --------
    matshow : Plot a matrix or an array as an image.
    
    Notes
    -----
    Unless *extent* is used, pixel centers will be located at integer
    coordinates. In other words: the origin will coincide with the center
    of pixel (0, 0).
    
    Examples
    --------
    
    .. plot:: mpl_examples/pylab_examples/image_demo.py
    
    Notes
    -----
    
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:
    
    * All positional and all keyword arguments.
    
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [53]:
fig, ax = plt.subplots()

im = ax.imshow(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')

cb = fig.colorbar(im, ax=ax)

contour

In [54]:
help(plt.contour)
Help on function contour in module matplotlib.pyplot:

contour(*args, **kwargs)
    Plot contours.
    
    :func:`~matplotlib.pyplot.contour` and
    :func:`~matplotlib.pyplot.contourf` draw contour lines and
    filled contours, respectively.  Except as noted, function
    signatures and return values are the same for both versions.
    
    :func:`~matplotlib.pyplot.contourf` differs from the MATLAB
    version in that it does not draw the polygon edges.
    To draw edges, add line contours with
    calls to :func:`~matplotlib.pyplot.contour`.
    
    
    Call signatures::
    
      contour(Z)
    
    make a contour plot of an array *Z*. The level values are chosen
    automatically.
    
    ::
    
      contour(X,Y,Z)
    
    *X*, *Y* specify the (x, y) coordinates of the surface
    
    ::
    
      contour(Z,N)
      contour(X,Y,Z,N)
    
    contour up to *N* automatically-chosen levels.
    
    ::
    
      contour(Z,V)
      contour(X,Y,Z,V)
    
    draw contour lines at the values specified in sequence *V*,
    which must be in increasing order.
    
    ::
    
      contourf(..., V)
    
    fill the ``len(V)-1`` regions between the values in *V*,
    which must be in increasing order.
    
    ::
    
      contour(Z, **kwargs)
    
    Use keyword args to control colors, linewidth, origin, cmap ... see
    below for more details.
    
    *X* and *Y* must both be 2-D with the same shape as *Z*, or they
    must both be 1-D such that ``len(X)`` is the number of columns in
    *Z* and ``len(Y)`` is the number of rows in *Z*.
    
    ``C = contour(...)`` returns a
    :class:`~matplotlib.contour.QuadContourSet` object.
    
    Optional keyword arguments:
    
      *corner_mask*: [ *True* | *False* | 'legacy' ]
        Enable/disable corner masking, which only has an effect if *Z* is
        a masked array.  If *False*, any quad touching a masked point is
        masked out.  If *True*, only the triangular corners of quads
        nearest those points are always masked out, other triangular
        corners comprising three unmasked points are contoured as usual.
        If 'legacy', the old contouring algorithm is used, which is
        equivalent to *False* and is deprecated, only remaining whilst the
        new algorithm is tested fully.
    
        If not specified, the default is taken from
        rcParams['contour.corner_mask'], which is True unless it has
        been modified.
    
      *colors*: [ *None* | string | (mpl_colors) ]
        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.
    
      *alpha*: float
        The alpha blending value
    
      *cmap*: [ *None* | Colormap ]
        A cm :class:`~matplotlib.colors.Colormap` instance or
        *None*. If *cmap* is *None* and *colors* is *None*, a
        default Colormap is used.
    
      *norm*: [ *None* | Normalize ]
        A :class:`matplotlib.colors.Normalize` instance for
        scaling data values to colors. If *norm* is *None* and
        *colors* is *None*, the default linear scaling is used.
    
      *vmin*, *vmax*: [ *None* | scalar ]
        If not *None*, either or both of these values will be
        supplied to the :class:`matplotlib.colors.Normalize`
        instance, overriding the default color scaling based on
        *levels*.
    
      *levels*: [level0, level1, ..., leveln]
        A list of floating point numbers indicating the level
        curves to draw, in increasing order; e.g., to draw just
        the zero contour pass ``levels=[0]``
    
      *origin*: [ *None* | 'upper' | 'lower' | 'image' ]
        If *None*, the first value of *Z* will correspond to the
        lower left corner, location (0,0). If 'image', the rc
        value for ``image.origin`` will be used.
    
        This keyword is not active if *X* and *Y* are specified in
        the call to contour.
    
      *extent*: [ *None* | (x0,x1,y0,y1) ]
    
        If *origin* is not *None*, then *extent* is interpreted as
        in :func:`matplotlib.pyplot.imshow`: it gives the outer
        pixel boundaries. In this case, the position of Z[0,0]
        is the center of the pixel, not a corner. If *origin* is
        *None*, then (*x0*, *y0*) is the position of Z[0,0], and
        (*x1*, *y1*) is the position of Z[-1,-1].
    
        This keyword is not active if *X* and *Y* are specified in
        the call to contour.
    
      *locator*: [ *None* | ticker.Locator subclass ]
        If *locator* is *None*, the default
        :class:`~matplotlib.ticker.MaxNLocator` is used. The
        locator is used to determine the contour levels if they
        are not given explicitly via the *V* argument.
    
      *extend*: [ 'neither' | 'both' | 'min' | 'max' ]
        Unless this is 'neither', contour levels are automatically
        added to one or both ends of the range so that all data
        are included. These added ranges are then mapped to the
        special colormap values which default to the ends of the
        colormap range, but can be set via
        :meth:`matplotlib.colors.Colormap.set_under` and
        :meth:`matplotlib.colors.Colormap.set_over` methods.
    
      *xunits*, *yunits*: [ *None* | registered units ]
        Override axis units by specifying an instance of a
        :class:`matplotlib.units.ConversionInterface`.
    
      *antialiased*: [ *True* | *False* ]
        enable antialiasing, overriding the defaults.  For
        filled contours, the default is *True*.  For line contours,
        it is taken from rcParams['lines.antialiased'].
    
      *nchunk*: [ 0 | integer ]
        If 0, no subdivision of the domain.  Specify a positive integer to
        divide the domain into subdomains of *nchunk* by *nchunk* quads.
        Chunking reduces the maximum length of polygons generated by the
        contouring algorithm which reduces the rendering workload passed
        on to the backend and also requires slightly less RAM.  It can
        however introduce rendering artifacts at chunk boundaries depending
        on the backend, the *antialiased* flag and value of *alpha*.
    
    contour-only keyword arguments:
    
      *linewidths*: [ *None* | number | tuple of numbers ]
        If *linewidths* is *None*, the default width in
        ``lines.linewidth`` in ``matplotlibrc`` is used.
    
        If a number, all levels will be plotted with this linewidth.
    
        If a tuple, different levels will be plotted with different
        linewidths in the order specified.
    
      *linestyles*: [ *None* | 'solid' | 'dashed' | 'dashdot' | 'dotted' ]
        If *linestyles* is *None*, the default is 'solid' unless
        the lines are monochrome.  In that case, negative
        contours will take their linestyle from the ``matplotlibrc``
        ``contour.negative_linestyle`` setting.
    
        *linestyles* can also be an iterable of the above strings
        specifying a set of linestyles to be used. If this
        iterable is shorter than the number of contour levels
        it will be repeated as necessary.
    
    contourf-only keyword arguments:
    
      *hatches*:
        A list of cross hatch patterns to use on the filled areas.
        If None, no hatching will be added to the contour.
        Hatching is supported in the PostScript, PDF, SVG and Agg
        backends only.
    
    
    Note: contourf fills intervals that are closed at the top; that
    is, for boundaries *z1* and *z2*, the filled region is::
    
        z1 < z <= z2
    
    There is one exception: if the lowest boundary coincides with
    the minimum value of the *z* array, then that minimum value
    will be included in the lowest interval.
    
    **Examples:**
    
    .. plot:: mpl_examples/pylab_examples/contour_demo.py
    
    .. plot:: mpl_examples/pylab_examples/contourf_demo.py
    
    .. plot:: mpl_examples/pylab_examples/contour_corner_mask.py
    
    
    
    Additional kwargs: hold = [True|False] overrides default hold state

In [55]:
fig, ax = plt.subplots()

cnt = ax.contour(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])

3D

In [56]:
from mpl_toolkits.mplot3d.axes3d import Axes3D

Surface plot

In [57]:
fig = plt.figure(figsize=(14,6))

# `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')

p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)

# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)
In [58]:
help(ax.plot_surface)
Help on method plot_surface in module mpl_toolkits.mplot3d.axes3d:

plot_surface(X, Y, Z, *args, **kwargs) method of matplotlib.axes._subplots.Axes3DSubplot instance
    Create a surface plot.
    
    By default it will be colored in shades of a solid color,
    but it also supports color mapping by supplying the *cmap*
    argument.
    
    The `rstride` and `cstride` kwargs set the stride used to
    sample the input data to generate the graph.  If 1k by 1k
    arrays are passed in the default values for the strides will
    result in a 100x100 grid being plotted.
    
    ============= ================================================
    Argument      Description
    ============= ================================================
    *X*, *Y*, *Z* Data values as 2D arrays
    *rstride*     Array row stride (step size), defaults to 10
    *cstride*     Array column stride (step size), defaults to 10
    *color*       Color of the surface patches
    *cmap*        A colormap for the surface patches.
    *facecolors*  Face colors for the individual patches
    *norm*        An instance of Normalize to map values to colors
    *vmin*        Minimum value to map
    *vmax*        Maximum value to map
    *shade*       Whether to shade the facecolors
    ============= ================================================
    
    Other arguments are passed on to
    :class:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`

Wire-frame plot

In [59]:
fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1, 1, 1, projection='3d')

p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)

复杂点的

In [60]:
fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1,1,1, projection='3d')

ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*np.pi, cmap=matplotlib.cm.coolwarm)

ax.set_xlim3d(-np.pi, 2*np.pi);
ax.set_ylim3d(0, 3*np.pi);
ax.set_zlim3d(-np.pi, 2*np.pi);

换个角度

In [61]:
fig = plt.figure(figsize=(12,6))

ax = fig.add_subplot(1,2,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(30, 45)

ax = fig.add_subplot(1,2,2, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(70, 30)

fig.tight_layout()