1. 程式人生 > 其它 >Matplotlib繪圖設定---顏色條設定

Matplotlib繪圖設定---顏色條設定

設定顏色條

對於圖形中由彩色的點、線、面構成的連續標籤,用顏色條來表示的效果比較好,在Matplotlib中,顏色條是一個獨立的座標軸。

可檢視形的顏色選擇可參考matplotlib配色方案。

Choosing Colormaps — Matplotlib 1.4.1 documentation

重點關注的配色方案

  • 順序配色方案:由一組連續的顏色構成的配色方案(例如binary 或 viridis)。
  • 互逆配色方案:通常有兩種互補的顏色構成,表示正反兩種含義(例如RdBu 或 PuOr)
  • 定性配色方案:隨機順序的一組顏色(例如rainbow 或 jet)
plt.imshow(
    X,
    cmap=None,
    norm=None,
    aspect=None,
    interpolation=None,
    alpha=None,
    vmin=None,
    vmax=None,
    origin=None,
    extent=None,
    shape=<deprecated parameter>,
    filternorm=1,
    filterrad=4.0,
    imlim=<deprecated parameter>,
    resample=None,
    url=None,
    *,
    data=None,
    **kwargs,
)
Docstring:
Display an image, i.e. data on a 2D regular raster.

Parameters
----------
X : array-like or PIL image
    The image data. Supported array shapes are:

    - (M, N): an image with scalar data. The data is visualized
      using a colormap.
    - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
    - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
      i.e. including transparency.

    The first two dimensions (M, N) define the rows and columns of
    the image.

    Out-of-range RGB(A) values are clipped.

cmap : str or `~matplotlib.colors.Colormap`, optional
    The Colormap instance or registered colormap name used to map
    scalar data to colors. This parameter is ignored for RGB(A) data.
    Defaults to :rc:`image.cmap`.

norm : `~matplotlib.colors.Normalize`, optional
    The `Normalize` instance used to scale scalar data to the [0, 1]
    range before mapping to colors using *cmap*. By default, a linear
    scaling mapping the lowest value to 0 and the highest to 1 is used.
    This parameter is ignored for RGB(A) data.

aspect : {'equal', 'auto'} or float, optional
    Controls the aspect ratio of the axes. The aspect is of particular
    relevance for images since it may distort the image, i.e. pixel
    will not be square.

    This parameter is a shortcut for explicitly calling
    `.Axes.set_aspect`. See there for further details.

    - 'equal': Ensures an aspect ratio of 1. Pixels will be square
      (unless pixel sizes are explicitly made non-square in data
      coordinates using *extent*).
    - 'auto': The axes is kept fixed and the aspect is adjusted so
      that the data fit in the axes. In general, this will result in
      non-square pixels.

    If not given, use :rc:`image.aspect` (default: 'equal').

interpolation : str, optional
    The interpolation method used. If *None*
    :rc:`image.interpolation` is used, which defaults to 'nearest'.

    Supported values are 'none', 'nearest', 'bilinear', 'bicubic',
    'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
    'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc',
    'lanczos'.

    If *interpolation* is 'none', then no interpolation is performed
    on the Agg, ps, pdf and svg backends. Other backends will fall back
    to 'nearest'. Note that most SVG renders perform interpolation at
    rendering and that the default interpolation method they implement
    may differ.

    See
    :doc:`/gallery/images_contours_and_fields/interpolation_methods`
    for an overview of the supported interpolation methods.

    Some interpolation methods require an additional radius parameter,
    which can be set by *filterrad*. Additionally, the antigrain image
    resize filter is controlled by the parameter *filternorm*.

alpha : scalar, optional
    The alpha blending value, between 0 (transparent) and 1 (opaque).
    This parameter is ignored for RGBA input data.

vmin, vmax : scalar, optional
    When using scalar data and no explicit *norm*, *vmin* and *vmax*
    define the data range that the colormap covers. By default,
    the colormap covers the complete value range of the supplied
    data. *vmin*, *vmax* are ignored if the *norm* parameter is used.

origin : {'upper', 'lower'}, optional
    Place the [0,0] index of the array in the upper left or lower left
    corner of the axes. The convention 'upper' is typically used for
    matrices and images.
    If not given, :rc:`image.origin` is used, defaulting to 'upper'.

    Note that the vertical axes points upward for 'lower'
    but downward for 'upper'.

    See the :doc:`/tutorials/intermediate/imshow_extent` tutorial for
    examples and a more detailed description.

extent : scalars (left, right, bottom, top), optional
    The bounding box in data coordinates that the image will fill.
    The image is stretched individually along x and y to fill the box.

    The default extent is determined by the following conditions.
    Pixels have unit size in data coordinates. Their centers are on
    integer coordinates, and their center coordinates range from 0 to
    columns-1 horizontally and from 0 to rows-1 vertically.

    Note that the direction of the vertical axis and thus the default
    values for top and bottom depend on *origin*:

    - For ``origin == 'upper'`` the default is
      ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``.
    - For ``origin == 'lower'`` the default is
      ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``.

    See the :doc:`/tutorials/intermediate/imshow_extent` tutorial for
    examples and a more detailed description.

filternorm : bool, optional, default: True
    A parameter for the antigrain image resize filter (see the
    antigrain documentation).  If *filternorm* is set, 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 : float > 0, 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'.

resample : bool, optional
    When *True*, use a full resampling method.  When *False*, only
    resample when the output image is larger than the input image.

url : str, optional
    Set the url of the created `.AxesImage`. See `.Artist.set_url`.

Returns
-------
image : `~matplotlib.image.AxesImage`

Other Parameters
----------------
**kwargs : `~matplotlib.artist.Artist` properties
    These parameters are passed on to the constructor of the
    `.AxesImage` artist.

See also
--------
matshow : Plot a matrix or an array as an image.

**X:**
影象資料。支援的陣列形狀是:
(M,N) :帶有標量資料的影象。資料視覺化使用色彩圖。
(M,N,3) :具有RGB值的影象(float或uint8)。
(M,N,4) :具有RGBA值的影象(float或uint8),即包括透明度。
前兩個維度(M,N)定義了行和列圖片,即圖片的高和寬;
RGB(A)值應該在浮點數[0, ..., 1]的範圍內,或者
整數[0, ... ,255]。超出範圍的值將被剪下為這些界限。
**cmap:**
將標量資料對映到色彩圖
顏色預設為:rc:image.cmap。
**norm :**
~matplotlib.colors.Normalize
如果使用scalar data ,則Normalize會對其進行縮放[0,1]的資料值內。
預設情況下,資料範圍使用線性縮放對映到顏色條範圍。 RGB(A)資料忽略該引數。
**aspect:**
{'equal','auto'}或float,可選
控制軸的縱橫比。該引數可能使影象失真,即畫素不是方形的。
equal:確保寬高比為1,畫素將為正方形。(除非畫素大小明確地在資料中變為非正方形,座標使用 extent )。
auto: 更改影象寬高比以匹配軸的寬高比。通常,這將導致非方形畫素。
**interpolation:**
str
使用的插值方法
支援的值有:'none', 'nearest', 'bilinear', 'bicubic','spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc','lanczos'.
如果interpolation = 'none',則不執行插值
**alpha:**
alpha值,介於0(透明)和1(不透明)之間。RGBA輸入資料忽略此引數。
**vmin, vmax : scalar,**
如果使用* norm 引數,則忽略 vmin , vmax *。
vmin,vmax與norm結合使用以標準化亮度資料。
**origin : {'upper', 'lower'}**
將陣列的[0,0]索引放在軸的左上角或左下角。
'upper'通常用於矩陣和影象。
請注意,垂直軸向上指向“下”但向下指向“上”。
**extent:(left, right, bottom, top)**
資料座標中左下角和右上角的位置。 如果為“無”,則定點陣圖像使得畫素中心落在基於零的(行,列)索引上。
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456789)
data = np.random.rand(25).reshape(5, 5)

#plt.imshow()繪製一組矩陣或陣列影象
#cmap設定配色方案,origin設定陣列的索引方向,aspect設定座標軸縱橫比,vmin和vmax設定顯示的值範圍,
#alpha設定透明度,interpolation設定插值方法(預設為None)
plt.imshow(data,cmap='viridis', origin='lower', aspect='auto',vmin=-0.8, vmax=0.8, alpha=0.7, interpolation='None')
#plt.colorbar()繪製簡單顏色條
plt.colorbar()
#xlim,ylim設定x軸和y軸的座標範圍
plt.imshow(data,cmap='viridis', origin='lower', aspect='auto',vmin=-0.8, vmax=0.8, alpha=0.7, interpolation='None')
plt.xlim(-1,5)
plt.ylim(5,-1)
plt.colorbar()
#interpolation用於設定插值方法
inter_list = ['nearest', 'bilinear', 'bicubic','spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc','lanczos']

fig = plt.figure()
fig.subplots_adjust(hspace=0.6, wspace=0.2)
for i,itype in zip(range(1,17),inter_list):
    ax = fig.add_subplot(4,4,i)
    ax.imshow(data, cmap='viridis', origin='lower', interpolation=itype)
    ax.set_title(itype)