• matplotlib简单整理


    安装:

    pip install matplotlib
    

    入门

    简单介绍:

    举个例子,在现实中,我们想要画一个图表,首先需要找一个可以画的地方来画,譬如一张纸,一块黑板等,这些承载图像的东西,称之为:figure

    然后,你需要画图,以黑板为例子,一个黑板上面可以画多个图表,这个图表可以看作是数学中的带有x,y轴 (Axis,即轴) 的区域。这个区域称之为 Axes 。每个图表(Axes)中都可以画多条线,这每条线都是一个Line2D(顾名思义,二维线条)对象。

    好了,现在,一个 Figure 可以有多个 Axes,每个 Axes 都有两条 Axis轴,每个 Axes 也可以有多个 Line2D。

    对于 Figure,可以设置 背景色,边框粗细,边框颜色,Figure 标题等内容。

    对于 Line2D,可以设置 线条的粗细,颜色,线上数据点的样式(也就是marker,标记点)等。

    对于Axis,每个 Axis 都有刻度(tick),刻度值(ticklabel) 等,并且可以设置主刻度(Major),副刻度等。

    图表组成

    spines:也就是图表的上下左右四个边框

    Marker:要画图,要先有数据,如果要将这些数据在图线上凸显出来,就是marker,marker控制数据点的显示样式,如圆点,三角形等。

    Legend:图例,给每条图线显示一个图例

    简单的例子:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()  # subplots() 可以创建 Axes,还有 figure
    ax.plot([1, 2, 3, 4], [1, 4, 2, 3])  # 在 axes 上画一些数据:(x轴,y轴)
    plt.show()
    

    plot()接受的输入参数格式,是 numpy.array or numpy.ma.masked_array ,如果用户输入的是列表,如上例所示,plt内部会自动进行转换。

    Figure

    可以看作一个作图区域,也就是一张画布,一个 figure 可以包含多个 axes(图表)

    fig = plt.figure()  # 创建一个空白 figure
    fig, ax = plt.subplots()  # 在figure上只创建一个 Axes
    fig, axs = plt.subplots(2, 2)  # 创建一个带有2x2格 Axes 的 figure;即一个拥有两行x两列,共4个 Axes 的 figure
    

    Axes

    也就是一个图表。一个 Axes 包含两个 Axis (坐标轴),坐标轴可以设置数据的限制: axes.Axes.set_xlim(0,20)(比如设置横坐标范围为:0-20),axes.Axes.set_ylim(),每一个坐标轴都有一个坐标轴的名字,可以通过 set_xlabel(), set_ylabel() 设置。

    Axis

    坐标轴,可以设置坐标的范围限制,可以设置 ticks (标记,也就是坐标轴上的刻度),也可以设置 ticklabels (刻度的名字,或者叫刻度值),刻度由 Locator 对象控制,刻度值由 Formatter 控制。

    两种代码风格:

    1. 面向对象
    x = np.linspace(0, 2, 100)
    
    # Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
    fig, ax = plt.subplots()  # Create a figure and an axes.
    ax.plot(x, x, label='linear')  # 此时可以单独对这个 Axes 画一条折线
    ax.plot(x, x**2, label='quadratic')  # 在这个 ax 上继续再画一条线
    ax.plot(x, x**3, label='cubic')  # 再画一条折线
    ax.set_xlabel('x label')  # 给 x轴 设置一个名字
    ax.set_ylabel('y label')  # 给 y轴 加一个名字
    ax.set_title("Simple Plot")  # 给 Axes 添加一个表名
    ax.legend()  # 添加一个图例
    
    1. pyplot形式
    x = np.linspace(0, 2, 100)
    
    plt.plot(x, x, label='linear')  # 画一个线,名字叫 linear
    plt.plot(x, x**2, label='quadratic')  # 再画一个线
    plt.plot(x, x**3, label='cubic')
    plt.xlabel('x label')
    plt.ylabel('y label')
    plt.title("Simple Plot")
    plt.legend()
    

    互动模式

    正常情况下写代码,需要在代码最后手动调用 plt.show() 来让图像显示,但是在互动模式下,你每输入一行代码,就可以实时让图表跟着变化。

    开启互动模式:

    import matplotlib.pyplot as plt
    plt.ion()
    plt.plot([1.6, 2.7])  # 此时就会显示图像了,不用 plt.show()
    

    关闭互动:

    import matplotlib.pyplot as plt
    plt.ioff()
    plt.plot([1.6, 2.7]) # 此时不会显示,需要执行一句 : plt.show()
    

    pyplot模式

    pyplot模式,基本上就是直接作图,不用 对象导向 的方式。具体对比可以看上文的”两种代码风格

    快速图表

    import matplotlib.pyplot as plt
    
    plt.plot([1, 2, 3, 4])      # 只提供了一列数据,会默认是y轴的数据,plt会据此自动生成一个x轴数据
    plt.ylabel('some numbers')
    plt.show()
    

    定制图表

    plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') # (x轴,y轴,格式);格式中的 r 代表 red 红色,o 表示用 圆点 标记数据点
    plt.axis([0, 6, 0, 20])    # 设置x轴和y轴的数据 :[xmin, xmax, ymin, ymax]
    plt.show()
    

    一次性画多条线

    import numpy as np
    
    # evenly sampled time at 200ms intervals
    t = np.arange(0., 5., 0.2)
    
    # red dashes, blue squares and green triangles
    plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') # 一次性画了三条线,plot() 返回的是个元组(line1,line2,line3)
    plt.show()
    

    不同类型图表

    names = ['group_a', 'group_b', 'group_c']
    values = [1, 10, 100]
    
    plt.figure(figsize=(9, 3)) # 设置画布大小
    
    plt.subplot(131)	# 绘制 1*3 个Axes,此时是第1个Axes。也就是画出三个Axes,排列方式是1行3列,当前选中这三个的第一个。
    plt.bar(names, values) # 在这第一个 Axes 上画一个柱状图
    plt.subplot(132)       # 1*3中的第2个
    plt.scatter(names, values)  # 第二个上画散点图
    plt.subplot(133)
    plt.plot(names, values)  # 第三个默认用折线图
    plt.suptitle('Categorical Plotting')
    plt.show()
    

    画图参数

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.plot(x, y, linewidth=2.0) # 参数 linewidth ,设置线条的宽度
    
    fig, ax = plt.subplots()  # 创建一个只有一个 axes 的 figure
    ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
    ax.set_xlabel("MY x") # 也可以使用函数设置某些参数
    
    Property Value Type
    alpha float :设置线条透明度
    animated [True | False]
    antialiased or aa [True | False]
    clip_box a matplotlib.transform.Bbox instance
    clip_on [True | False]
    clip_path a Path instance and a Transform instance, a Patch
    color or c any matplotlib color :线条颜色
    contains the hit testing function
    dash_capstyle ['butt'
    dash_joinstyle ['miter'
    dashes sequence of on/off ink in points
    data (np.array xdata, np.array ydata)
    figure a matplotlib.figure.Figure instance
    label any string:线条名称
    linestyle or ls [ '-'
    linewidth or lw float value in points : 线宽
    marker [ '+'
    markeredgecolor or mec any matplotlib color
    markeredgewidth or mew float value in points
    markerfacecolor or mfc any matplotlib color
    markersize or ms float :marker显示大小
    markevery [ None | integer | (startind, stride) ]
    picker used in interactive line selection
    pickradius the line pick selection radius
    solid_capstyle ['butt'
    solid_joinstyle ['miter'
    transform a matplotlib.transforms.Transform instance
    visible [True | False]:是否可见
    xdata np.array
    ydata np.array
    zorder any number:似乎是设置线条图层顺序的,譬如多条线互相遮盖时能用到

    添加文本

    在图表中,可以在任意位置添加文本

    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(10000)
    
    # the ogram of the data
    n, bins, patches = plt.(x, 50, density=1, facecolor='g', alpha=0.75) # 柱状图
    
    
    plt.xlabel('Smarts')
    plt.ylabel('Probability')
    plt.title('ogram of IQ')d
    plt.text(60, .025, r'$mu=100, sigma=15$') # 在坐标(60,0.025)处设置文本:mu=100.., $等字符是 TeX表达式 格式。
    plt.axis([40, 160, 0, 0.03])
    plt.grid(True) # 添加网格
    plt.show()
    

    数据标注

    可以给某个数据点添加标注

    ax = plt.subplot()
    
    t = np.arange(0.0, 5.0, 0.01)
    s = np.cos(2*np.pi*t)
    line, = plt.plot(t, s, lw=2)
    
    # 标注文字:local max, 标注的数据是(2,1), 文本放置在坐标 (3,1.5),添加了一个箭头函数
    plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05),)
    
    plt.ylim(-2, 2)
    plt.show()
    

    非线性坐标轴

    如果你有一些特殊数据,是指数型增长的,可以使用特殊坐标轴,看下图的 y轴 就明白了。

    # Fixing random state for reproducibility
    np.random.seed(19680801)
    
    # make up some data in the open interval (0, 1)
    y = np.random.normal(loc=0.5, scale=0.4, size=1000)
    y = y[(y > 0) & (y < 1)]
    y.sort()
    x = np.arange(len(y))
    
    # plot with various axes scales
    plt.figure()
    
    # linear
    plt.subplot(221)
    plt.plot(x, y)
    plt.yscale('linear')
    plt.title('linear')
    plt.grid(True)
    
    # log
    plt.subplot(222)
    plt.plot(x, y)
    plt.yscale('log')
    plt.title('log')
    plt.grid(True)
    
    # symmetric log
    plt.subplot(223)
    plt.plot(x, y - y.mean())
    plt.yscale('symlog', linthresh=0.01)
    plt.title('symlog')
    plt.grid(True)
    
    # logit
    plt.subplot(224)
    plt.plot(x, y)
    plt.yscale('logit')
    plt.title('logit')
    plt.grid(True)
    # Adjust the subplot layout, because the logit one may take more space
    # than usual, due to y-tick labels like "1 - 10^{-3}"
    plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                        wspace=0.35)
    
    plt.show()
    

    matplotlib.pyplot.plot

    plot的几种用法:

    plot(x, y)        # 用默认样式画 x,y
    plot(x, y, 'bo')  # 画x,y,用蓝色圆点标记数据,b代表蓝色,o代表marker的样式为圆点
    plot(y)           # plot y using x as index array 0..N-1(x用默认值)
    plot(y, 'r+')     # 同上,r代表红色,+代表某种marker样式
    
    plot(x, y, 'go--', linewidth=2, markersize=12) # 也可以用 line2D 属性作为关键字参数,来控制样式
    
    plot([x], y, [fmt], *, data=None, **kwargs)
    plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
    

    参数:

    x, y : x轴和y轴的数据,列表类型或者 numpy.array

    fmt :可选。字符串类型,表示图形的样式。fmt = '[marker][line][color]',如:“o-r"

    返回值:plot() 返回一组表达图形的 line2D 对象。

    Line2D

    plot() 方法返回的一组图形对象,就是Line2D,譬如:

    import matplotlib.pyplot as plt
    
    line, = plt.plot([1,2,3,4]) # line 就是一个 Line2D 对象,它就是绘画出来的图表(因为返回值是个list,所以用,来解包)
    plt.show()
    

    Line2D有很多属性,用来控制绘制的图表的样式,这些属性可以作为关键字参数,传递给plot()。如:

    import matplotlib.pyplot as plt
    plt.ion()
    
    line, = plt.plot([1,2,3,4],linewidth=2,color='red',label="fig1") # 传递参数,此时line 已经绘制完毕了
    

    针对这些属性,line2D 对象还有get_xx, set_xx 方法,来设置这些属性。更多请见:https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D

    譬如:

    >>> import matplotlib.pyplot as plt
    >>> plt.ion()
    >>> line, = plt.plot([1,2,3,4],linewidth=2,color='red',label="fig1")
    >>> line.set_color("green") # 上面设置颜色为红色,此处重新设置为绿色
    >>> print(line.get_color())
    green
    
    

    属性:

    Property Description
    agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha scalar or None:设置线条透明度
    animated bool
    antialiased or aa bool
    clip_box Bbox
    clip_on bool
    clip_path Patch or (Path, Transform) or None
    color or c color
    contains unknown
    dash_capstyle CapStyle or {'butt', 'projecting', 'round'}
    dash_joinstyle JoinStyle or {'miter', 'round', 'bevel'}
    dashes sequence of floats (on/off ink in points) or (None, None)
    data (2, N) array or two 1D arrays
    drawstyle or ds {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
    figure Figure
    fillstyle {'full', 'left', 'right', 'bottom', 'top', 'none'}
    gid str
    in_layout bool
    label object:线条名称
    linestyle or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}:线条样式
    linewidth or lw float
    marker marker style string, Path or MarkerStyle
    markeredgecolor or mec color
    markeredgewidth or mew float
    markerfacecolor or mfc color
    markerfacecoloralt or mfcalt color
    markersize or ms float
    markevery None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
    path_effects AbstractPathEffect
    picker float or callable[[Artist, Event], tuple[bool, dict]]
    pickradius float
    rasterized bool
    sketch_params (scale: float, length: float, randomness: float)
    snap bool or None
    solid_capstyle CapStyle or {'butt', 'projecting', 'round'}
    solid_joinstyle JoinStyle or {'miter', 'round', 'bevel'}
    transform matplotlib.transforms.Transform
    url str
    visible bool
    xdata 1D array
    ydata 1D array
    zorder float:多个图表绘制在一个Axes上,可能有重叠,此处设置顺序

    marker 属性的可选值:

    Markers

    character description
    '.' 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
    '8' octagon marker
    's' square marker
    'p' pentagon marker
    'P' plus (filled) marker
    '*' star marker
    'h' hexagon1 marker
    'H' hexagon2 marker
    '+' plus marker
    'x' x marker
    'X' x (filled) marker
    'D' diamond marker
    'd' thin_diamond marker
    `' '`
    '_' hline marker

    linestyle 属性的可选值:

    Line Styles

    character description
    '-' 实线
    '--' 虚线
    '-.' 虚线和.
    ':' 点组成的线

    color 属性的值:

    除了下方这些,还可以设置成全名如:color = "green",或者16进制颜色字符串:color="#008000"

    character color
    'b' blue
    'g' green
    'r' red
    'c' cyan
    'm' magenta
    'y' yellow
    'k' black
    'w' white

    常用方法:

    get_color(self)

    Return the line color.

    See also set_color.

    get_data(self, orig=True)[source]

    Return the line data as an (xdata, ydata) pair.

    If orig is True, return the original data.

    get_linestyle(self)[source]

    Return the linestyle.

    See also set_linestyle.

    get_linewidth(self)[source]

    Return the linewidth in points.See also set_linewidth.

    get_ls(self)

    Alias for get_linestyle.

    get_lw(self)

    Alias for get_linewidth.

    get_xdata(self, orig=True)[source]

    Return the xdata.

    If orig is True, return the original data, else the processed data.

    get_xydata(self)[source]

    Return the xy data as a Nx2 numpy array.

    get_ydata(self, orig=True)[source]

    Return the ydata.If orig is True, return the original data, else the processed data.

    set_color(self, color)[source]

    Set the color of the line.

    set_linestyle(self, ls)[source]

    Set the linestyle of the line.

    set_linewidth(self, w)[source]

    Set the line width in points.

    set_marker(self, marker)[source]

    Set the line marker.

    set_markersize(self, sz)[source]

    Set the marker size in points.

    set_xdata(self, x)[source]

    Set the data array for x.

    set_ydata(self, y)[source]

    Set the data array for y.

    matplotlib.pyplot.subplot

    添加一个Axes到当前figure

    基本用法:

    subplot(nrows, ncols, index, **kwargs)
    subplot(pos, **kwargs)
    subplot(**kwargs)
    subplot(ax)
    

    最常用的参数:

    arg:一个3位数,或者(rows,cols,index)类型,譬如:subplot(221); 意思是:绘制2x2个空白的Axes,当前默认是2x2中的第1*个Axes。也就是两行,两列四个Axes,当前默认是第一个Axes。也可以写成:subplot(2,2,1)。subplot(2,2,(1,2)):创建2x2个Axes,当前的Axes横跨了第1,2个Axes,也就是说当前的Axes相当于合并了第一行的Axes,此时创建的是上面一个占据两个位置的Axes,下面两个正常的Axes,共3个Axes。

    sharex, shareyAxes 类型,和传递的 Axes 实例共享 x,y轴的设置。

    返回值:一个Axes实例

    举例:

    plt.subplot(221)
    
    # equivalent but more general
    ax1 = plt.subplot(2, 2, 1)
    
    # add a subplot with no frame
    ax2 = plt.subplot(222, frameon=False)
    
    # add a polar subplot
    plt.subplot(223, projection='polar')
    
    # add a red subplot that shares the x-axis with ax1
    plt.subplot(224, sharex=ax1, facecolor='red')
    
    # delete ax2 from the figure
    plt.delaxes(ax2)
    
    # add ax2 to the figure again
    plt.subplot(ax2)
    
    # make the first axes "current" again
    plt.subplot(221)
    

    matplotlib.pyplot.subplots

    matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

    参数:

    nrows,ncols: 数字。创建几行几列的图表区域

    返回值:fig,axes; 返回一个figure,一组 axes。

    # 默认创建一个 axes 
    fig, ax = plt.subplots()
    
    # 创建多个axes
    fig, axs = plt.subplots(2, 2)
    
    # using tuple unpacking for multiple Axes
    fig, (ax1, ax2) = plt.subplots(1, 2)
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    

    matplotlib.figure

    常用参数:

    figsize: 浮点数元组:(num1,num2), 设置图表的 宽,高的英寸数,默认:[6.4, 4.8]

    dpi:浮点数,设置每英寸的点数(可以理解为像素),默认:100

    facecolor: 设置 figure 的背景色,默认:白色

    edgecolor: figure 边框的颜色,默认:白色

    frameon: figure 边框开关选项,布尔类型,默认:True

    import matplotlib.pyplot as plt
    
    fig = plt.figure(edgecolor='red',linewidth=20,frameon=True,facecolor="green")
    ax1 = fig.add_subplot()
    ax1.plot([1,2,3,4])
    plt.show()
    

    Figure可能会用到的方法:

    add_axes(rect, projection=None, polar=False, **kwargs)

    在 figure 中添加一个 axes绘图区域。

    参数:

    rect:一组浮点数,如[0.2,0.3,0.4,0.6],代表[left, bottom, width, height],也就是在figure中的位置。

    返回值:Axes

    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax1 = fig.add_subplot()
    ax1.plot([1,2,3,4])
    
    ax2 = fig.add_axes([0,0,0.5,0.5]) 
    ax2.plot([1,2,3,4])
    
    plt.show()
    

    add_subplot(nrows, ncols, index, **kwargs)

    添加一个 Axes 到作图区,返回这个 Axes 对象。

    参数:

    nrows,ncols: 创建一个几行几列的 Axes 矩阵。

    Index: 几行几列中的第几个 Axes 区域

    sharex, sharey:和给定的 Axes 共享x/y轴。

    label: 返回的Axes 的label

    **kwargs:

    Property Description
    adjustable {'box', 'datalim'}
    agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha scalar or None
    anchor 2-tuple of floats or {'C', 'SW', 'S', 'SE', ...}
    animated bool
    aspect {'auto', 'equal'} or float
    autoscale_on bool
    autoscalex_on bool
    autoscaley_on bool
    axes_locator Callable[[Axes, Renderer], Bbox]
    axisbelow bool or 'line'
    box_aspect float or None
    clip_box Bbox
    clip_on bool
    clip_path Patch or (Path, Transform) or None
    contains unknown
    facecolor or fc color
    figure Figure
    frame_on bool
    gid str
    in_layout bool
    label object
    navigate bool
    navigate_mode unknown
    path_effects AbstractPathEffect
    picker None or bool or float or callable
    position [left, bottom, width, height] or Bbox
    prop_cycle unknown
    rasterization_zorder float or None
    rasterized bool
    sketch_params (scale: float, length: float, randomness: float)
    snap bool or None
    title str
    transform Transform
    url str
    visible bool
    xbound unknown
    xlabel str
    xlim (bottom: float, top: float)
    xmargin float greater than -0.5
    xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
    xticklabels unknown
    xticks unknown
    ybound unknown
    ylabel str
    ylim (bottom: float, top: float)
    ymargin float greater than -0.5
    yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
    yticklabels unknown
    yticks unknown
    zorder float
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax1 = fig.add_subplot(2,2,1)
    ax2 = fig.add_subplot(2,2,2)
    ax3 = fig.add_subplot(2,2,(3,4)) # 第三个 Axes 横跨 (3,4),所以占据两个位置,相当于Excel合并单元格
    ax1.plot([1,2,3])
    ax2.plot([1,2,3])
    ax3.plot([1,2,3])
    plt.show()
    

    align_labels

    同时对齐 x轴和y轴。

    align_xlabels(self, axs=None)

    对齐同一列subplots的x轴

    align_ylabels(self, axs=None)

    对齐同一列subplots的y轴

    autofmt_xdate(self, bottom=0.2, rotation=30, ha='right', which='major')

    针对日期格式的坐标轴,设置格式。

    bottom:距离底部的距离。

    rotation:是刻度值标签(ticklabel)旋转角度,防止刻度值互相遮盖。

    ha:{'left', 'center', 'right'}, default: 'right',x轴标签的水平排列方式(horizontal )

    which:{'major', 'minor', 'both'}, default: 'major', 针对哪种标签进行设置,是主刻度的标签,还是更小子刻度的标签

    clear(self, keep_observers=False)

    清除当前figure所有的内容,和 clf() 相同。

    delaxes(self, ax)

    从 figure 中删除 Axes

    gca(self, **kwargs)

    Get the current Axes,获取当前的Axes,如果没有会自动创建一个。

    **kwargs:

    Property Description
    adjustable {'box', 'datalim'}
    agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha scalar or None
    anchor 2-tuple of floats or {'C', 'SW', 'S', 'SE', ...}
    animated bool
    aspect {'auto', 'equal'} or float
    autoscale_on bool
    autoscalex_on bool
    autoscaley_on bool
    axes_locator Callable[[Axes, Renderer], Bbox]
    axisbelow bool or 'line'
    box_aspect float or None
    clip_box Bbox
    clip_on bool
    clip_path Patch or (Path, Transform) or None
    contains unknown
    facecolor or fc color
    figure Figure
    frame_on bool
    gid str
    in_layout bool
    label object
    navigate bool
    navigate_mode unknown
    path_effects AbstractPathEffect
    picker None or bool or float or callable
    position [left, bottom, width, height] or Bbox
    prop_cycle unknown
    rasterization_zorder float or None
    rasterized bool
    sketch_params (scale: float, length: float, randomness: float)
    snap bool or None
    title str
    transform Transform
    url str
    visible bool
    xbound unknown
    xlabel str
    xlim (bottom: float, top: float)
    xmargin float greater than -0.5
    xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
    xticklabels unknown
    xticks unknown
    ybound unknown
    ylabel str
    ylim (bottom: float, top: float)
    ymargin float greater than -0.5
    yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
    yticklabels unknown
    yticks unknown
    zorder float

    get_axes(self)

    返回当前figure的所有 Axes 列表。

    legend(self, **args*, **kwargs)

    添加图例

    三种方式:

    legend()  # 
    legend(labels)
    legend(handles, labels)
    
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot()
    # 1. 添加图例,使用 默认的 label
    ax.plot([1, 2, 3], label='Inline label')
    fig.legend()
    
    # 2. 设置label后,legend使用这个值作为默认值
    line, = ax.plot([1, 2, 3])
    line.set_label('Label via method')
    fig.legend()
    
    # 3. 批量给每条线配置一个名称作为图例上显示的名称,会覆盖之前设置的label
    line1, = ax.plot([2,3,4],label="aaa") # 此处的aaa会被下面的 label1 覆盖掉
    line2, = ax.plot([2,3,9])
    line3, = ax.plot([2,3,23])
    
    fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
    

    常用的参数:

    loc: 图例在figure中的位置。字符串或者数字,可选参数如下

    Location String Location Code mean
    'best' 0 自适应
    'upper right' 1 右上角
    'upper left' 2 左上角
    'lower left' 3 ..
    'lower right' 4 ..
    'right' 5 右侧
    'center left' 6
    'center right' 7
    'lower center' 8
    'upper center' 9
    'center' 10

    ncol: 数字。将图例分成几列显示,适用于很多图例排列太长的情况

    savefig(self, fname, ***, transparent=None, **kwargs)

    保存当前的figure

    savefig(fname, dpi=None, facecolor='w', edgecolor='w',
            orientation='portrait', papertype=None, format=None,
            transparent=False, bbox_inches=None, pad_inches=0.1,
            frameon=None, metadata=None)
    

    set_alpha(self, alpha)

    设置 alpha的值。可以理解为透明度。范围0-1

    show(self, warn=True)

    展示图形窗口

    subplots(self, nrows=1, ncols=1, ***, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)

    添加一组 subplots 到 figure

    参数:

    nrows:几行

    ncols:几列

    sharex,sharey:bool or {'none', 'all', 'row', 'col'}, default: False;all代表所有子图共享某个坐标轴,row代表每个子图共享x轴.......

    返回值:一个Axes,或者一组Axes

    实例:

    # First create some toy data:
    x = np.linspace(0, 2*np.pi, 400)
    y = np.sin(x**2)
    
    # Create a figure
    plt.figure()
    
    # Create a subplot
    ax = fig.subplots()
    ax.plot(x, y)
    ax.set_title('Simple plot')
    
    # Create two subplots and unpack the output array immediately
    ax1, ax2 = fig.subplots(1, 2, sharey=True)
    ax1.plot(x, y)
    ax1.set_title('Sharing Y axis')
    ax2.scatter(x, y)
    
    # Create four polar Axes and access them through the returned array
    axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
    axes[0, 0].plot(x, y)
    axes[1, 1].scatter(x, y)
    
    # Share a X axis with each column of subplots
    fig.subplots(2, 2, sharex='col')
    
    # Share a Y axis with each row of subplots
    fig.subplots(2, 2, sharey='row')
    
    # Share both X and Y axes with all subplots
    fig.subplots(2, 2, sharex='all', sharey='all')
    
    # Note that this is the same as
    fig.subplots(2, 2, sharex=True, sharey=True)
    

    subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

    调整Axes的位置。

    left,bottom,right,top:是子图Axes距离figure边缘的距离。类型:分数(小数)如0.25

    wspace: 子图左右之间的间距,类型:分数

    hspace:子图上下之间的间距

    suptitle(self, t, **kwargs)

    给figure添加一个居中的子标题。

    参数:

    t:字符串。标题内容

    x:浮点数。默认0.5,标题文本所在的x坐标

    y:浮点树。默认0.98,标题文本所在的y坐标

    ha:{'center', 'left', 'right'}, default: center; 水平对齐方式(依据x,y)

    va:{'top', 'center', 'bottom', 'baseline'}, default: top; 垂直对齐方式

    fontsize: 字体大小。float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

    返回值:标题文本

    text(self, x, y, s, fontdict=None, **kwargs)

    添加一个文本到figure,返回值:这段文本

    x,y: 放置文本的位置,[0-1]之间的浮点数。

    s:文本内容

    tight_layout(self, ***, pad=1.08, h_pad=None, w_pad=None, rect=None)

    调整subplots之间的间距(子图上下左右之间)

    matplotlib.axes

    折线图:Axes.plot()

    见上文 matplotlib.pyplot.plot

    散点图:Axes.scatter()

    Axes.scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)
    

    参数:

    x,y: x,y轴数据,列表类型的数据

    s:每个数据点对应的marker的size大小;可以是一个浮点类型,也可以浮点树的列表

    c:每个数据点的颜色;类型可以是单独的颜色,也可以是颜色的列表

    marker: 数据点的样式,markerstyle

    cmap:colormap,只有当 c 参数是一组浮点数时才会用到此参数

    alpha:浮点数;0-1,0代表透明,1代表不透明

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    x = [1,2,3,4,5]
    y = [1,2,3,4,5]
    s = [1,2,100,4,10] # 给每个不同的数据点设置大小
    c = ['r','b','g','k','k'] # 设置颜色
    
    fig, ax = plt.subplots()
    ax.scatter(x, y, s, c,marker='o')
    
    plt.show()
    

    柱状图:Axes.bar()

    Axes.bar(self, x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
    

    参数:

    x: 浮点或列表

    height: 浮点或列表;每个柱的高度,y轴的值

    浮点或列表;每个柱的宽度,默认0.8

    bottom: 柱的底部y轴所在位置。默认0

    align:{'center', 'edge'}, default: 'center';edge代表将柱状图的左侧和x坐标对齐。如果想要右边对齐,传递一个负数的宽度

    color:颜色,或者颜色列表

    edgecolor:颜色或者颜色列表;设置柱边缘颜色

    linewidth:柱边缘宽度,浮点数或者浮点树列表。

    tick_label: 字符串或字符串列表。

    xerr, yerr: float or array-like of shape(N,) or shape(2, N), optional。暂且理解为一个数据点的误差范围,xerr会基于数据点画一条横线,yerr会会一条竖线

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    x = [1,2,3,4,5]
    h = [1,2,3,4,5]
    c = ['r','b','g','grey','y']
    
    fig, ax = plt.subplots()
    ax.bar(x, h,color=c,tick_label=x) # 第一组数据,默认以0为底部起点
    ax.bar(x,h,bottom=h,color=c[::-1]) # 第二组数据,以第一组数据值的高度为起点,这样就叠加起了两组数据
    
    plt.show()
    

    水平横向柱状图:Axes.barh()

    Axes.barh(self, y, width, height=0.8, left=None, *, align='center', **kwargs)
    

    参数:

    y: 浮点或列表

    height: 浮点或列表;每个柱的高度,y轴的值

    浮点或列表;每个柱的宽度,默认0.8

    left: 柱的底部x轴所在位置。默认0

    align:{'center', 'edge'}, default: 'center';edge代表将柱状图的左侧和x坐标对齐。如果想要右边对齐,传递一个负数的宽度

    color:颜色,或者颜色列表

    edgecolor:颜色或者颜色列表;设置柱边缘颜色

    linewidth:柱边缘宽度,浮点数或者浮点树列表。

    tick_label: 字符串或字符串列表。

    xerr, yerr: float or array-like of shape(N,) or shape(2, N), optional。暂且理解为一个数据点的误差范围,xerr会基于数据点画一条横线,yerr会会一条竖线

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    y = [1,2,3,4,5]
    h = [10,2,3,4,5]
    c = ['r','b','g','grey','y']
    
    fig, ax = plt.subplots()
    ax.barh(y, h,color=c,tick_label=y) # 默认以0为底部起点
    
    plt.show()
    

    柱状图数据标签:Axes.bar_label()

    Axes.bar_label(self, container, labels=None, *, fmt='%g', label_type='edge', padding=0, **kwargs)
    

    给柱状图的每个数据添加标签

    参数:

    container: 从 bar(),barh() 返回的数据容器

    labels: 数组类型的文本,如果没有提供文本内容,会用数据值来作为标签。

    fmt:字符串。默认“%g"

    label_type: {'edge', 'center'}, default: 'edge'; center会在柱状图的柱子中间添加数据标签,edge会在柱子的末端添加数据标签

    padding: float, default: 0,数据标签距离柱子末端的距离

    import matplotlib.pyplot as plt
    import numpy as np
    
    N = 5
    menMeans = (20, 35, 30, 35, -27)
    womenMeans = (25, 32, 34, 20, -25)
    menStd = (2, 3, 4, 1, 2) # 值的误差
    womenStd = (3, 5, 2, 3, 3)
    ind = np.arange(N)    # x轴值
    width = 0.35       # 柱子宽度
    
    fig, ax = plt.subplots()
    
    p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
    p2 = ax.bar(ind, womenMeans, width,bottom=menMeans, yerr=womenStd, label='Women')
    
    ax.axhline(0, color='grey', linewidth=0.8) # 添加一条水平横线,位置是y轴0处...
    ax.set_ylabel('Scores')
    ax.set_title('Scores by group and gender')
    ax.set_xticks(ind)
    ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
    ax.legend()
    
    # Label with label_type 'center' instead of the default 'edge'
    ax.bar_label(p1, label_type='center') # 给柱子中间加上数据值标签
    ax.bar_label(p2, label_type='center') # 给第二组数据也加上标签
    ax.bar_label(p2) # 不知道为啥,再加一遍标签,竟然是汇总的数据值
    
    plt.show()
    

    饼图:Axes.pie

    Axes.pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=0, 0, frame=False, rotatelabels=False, *, normalize=None, data=None)
    

    参数:

    x:一维数组。存储每个区域的数值(x之和尽可能<=1,也就是事先求一下百分比)

    explode:长度和x相同的一维数组,默认None;设置区域的分离突出

    labels:列表,默认None;每个区域的label

    colors:数组类型,默认None;每个区域的颜色

    autopct:None或者可调用的函数或字符串。默认None;

    pctistance:浮点数,默认:0.6;

    shadow:bool类型,是否加阴影

    normalize:None或bool。如果是True,总会让x正常化(x之和=1),然后画一个全饼图;如果是False,当 sum(x) <= 1时,画一个缺失的饼图(不补全,因为和<1),如果 sum(x) >1,会报错!

    labeldistance:浮点或者None;默认1.1;每个区域label到饼图的距离,如果None,则不显示label。

    startangle:浮点,默认0度;饼图的旋转角度。

    radius:浮点,默认1;饼图半径。

    counterclock:bool,默认True;每一块的顺序,是顺时针还是逆时针方向。

    wedgeprops:字典类型;默认:none;每一块对象的属性,如 wedgeprops = {'linewidth': 3} 设置每一块区域的边缘线宽度。

    center:(浮点,浮点),默认(0,0);图表中心点的坐标。

    frame:bool,默认:False;如果是True,会画出Axes的边框。

    totatelabels:bool,默认:False;如果是True,自动旋转每一块区域的label一定的角度。

    注意:

    如果饼图不是正圆型,可以通过:Axes.set_aspect('equal')来设置。

    import matplotlib.pyplot as plt
    
    # Pie chart, where the slices will be ordered and plotted counter-clockwise:
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
    
    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90)
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
    
    plt.show()
    

    直方图:Axes.hist

    Axes.hist(self, x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)
    

    参数:

    x:(n,) array or sequence of (n,) arrays;直方图的输入值

    bins:int or sequence or str, default: rcParams["hist.bins"] (default: 10);条少个条形

    range:tuple or None, default: None ; 直方图的上下边缘范围

    density:bool, default: False ; 直方图的密度

    weights:(n,) array-like or None, default: None;权重

    cumulative:bool or -1, default: False;是否需要计算累计频数或频率;

    bottom:array-like, scalar, or None, default: None; 每个直方图的底部边缘位置

    histtype:{'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar'

    align:{'left', 'mid', 'right'}, default: 'mid'

    orientation:{'vertical', 'horizontal'}, default: 'vertical'

    rwidth:float or None, default: None;设置直方图条形宽度的百分比

    log:bool, default: False;True的话,会将坐标轴设置成对数型

    color:color or array-like of colors or None, default: None

    label:str or None, default: None

    stacked:bool, default: False;如果有多组数据,会将多组数据叠在一起的形式

    竖线:Axes.vlines

    Axes.vlines(self, x, ymin, ymax, colors=None, linestyles='solid', label='', *, data=None, **kwargs)
    

    参数:

    x:浮点或数组类型。在哪些x轴值上画线

    ymin,ymax:浮点或数组。线的开头和结尾。

    colors:颜色的列表。

    linestyles:{'solid', 'dashed', 'dashdot', 'dotted'}, optional

    label:字符串。默认“”

    横线:Axes.hlines

    Axes.hlines(self, y, xmin, xmax, colors=None, linestyles='solid', label='', *, data=None, **kwargs)[source]
    

    参数:

    y:浮点或数组类型。在哪些y轴值上画线

    xmin,xmax:浮点或数组。线的开头和结尾。

    colors:颜色的列表。

    linestyles:{'solid', 'dashed', 'dashdot', 'dotted'}, optional

    label:字符串。默认:“”

    注释:Axes.annotate

    Axes.annotate(self, text, xy, *args, **kwargs)
    

    在xy位置处放一个注释点

    参数:

    text:字符串,注释内容

    xy:(浮点,浮点);要注释的数据点的位置

    xytext:(浮点,浮点);默认xy处。

    xycoords:默认data;就是xy这个值所处的坐标系统,类型可以是字符串,函数,(浮点,浮点)或者Artist等。有以下这些字符串类型:

    Value Description
    'figure points' Points from the lower left of the figure
    'figure pixels' Pixels from the lower left of the figure
    'figure fraction' Fraction of figure from lower left
    'subfigure points' Points from the lower left of the subfigure
    'subfigure pixels' Pixels from the lower left of the subfigure
    'subfigure fraction' Fraction of subfigure from lower left
    'axes points' Points from lower left corner of axes
    'axes pixels' Pixels from lower left corner of axes
    'axes fraction' Fraction of axes from lower left
    'data' Use the coordinate system of the object being annotated (default)
    'polar' (theta, r) if not native 'data' coordinates

    textcoords:xytext所处的坐标系。默认xycoords;

    arrowprops:字典;在 xy 和 xytext 之间画一条箭头线。

    remain

    剩下的干不动了,有需求就看API文档吧

    https://matplotlib.org/stable/api/axes_api.html

  • 相关阅读:
    Python写出LSTM-RNN的代码
    TensorFlow 实现 RNN 入门教程
    RNN与应用案例:注意力模型与机器翻译
    RNN入门
    内积(又名点积)
    词袋模型(BOW, bag of words)
    softmax
    Dropout
    随机梯度下降法
    L1范式和L2范式
  • 原文地址:https://www.cnblogs.com/wztshine/p/15101086.html
Copyright © 2020-2023  润新知