Python中matplotlib模块解析
中文网:https://www.matplotlib.org.cn/
中文网:https://www.osgeo.cn/matplotlib/
官网:https://matplotlib.org/stable/index.html
一、简介
pylab结合了pyplot和numpy,对交互式使用来说比较方便,既可以画图又可以进行简单的计算。但是,对于一个项目来说,建议分别倒入使用
二、运用
1、简单图画
#(1)导入模块 import matplotlib.pyplot as plt import numpy as np #(2)构造数据对象 x=np.array([1,2,3,4,]) y=x*2 #(3)新建图画板对象:第一个参数表示的是编号,第二个表示的是图表的长宽 obj = plt.figure(num = 2, figsize=(8, 5)) #(4)调用画图方法:marker='o'表示标记坐标点的样式,color='red'表示线颜色,inewidth=1.0表示线宽,linestyle='--'表示线样式,markersize表示标记样式大小;x可省略,默认[0,1..,N-1]递增 plt.plot(x,y,marker='o',color="r",linewidth=1.0, linestyle='--',markersize=12,label='label') #(5)呈现图画 plt.show()
2、常见画图方法的参数说明
(1)plt.plot()画点线连接图
marker='o'表示标记坐标点的样式,常用标记方式如下
============= =============================== 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 ``'|'`` vline marker ``'_'`` hline marker ============= ===============================
color='red' #表示线颜色,也可以用颜色的十六进制字符串表示,常用颜色如下
============= =============================== character color ============= =============================== ``'b'`` blue ``'g'`` green ``'r'`` red ``'c'`` cyan ``'m'`` magenta ``'y'`` yellow ``'k'`` black ``'w'`` white ============= ===============================
inewidth=1.0 #表示线宽,float类型
linestyle='--' #表示线样式,常用样式如下
============= =============================== character description ============= =============================== ``'-'`` solid line style ``'--'`` dashed line style ``'-.'`` dash-dot line style ``':'`` dotted line style ============= ===============================
plot画图方法其他可选参数如下:
Here is a list of available `.Line2D` properties: Properties: 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.Path` or `~.markers.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
(2)plt.scatter()画散点图
# s表示点的大小,默认rcParams['lines.markersize']**2
L2 , =plt.scatter(x,y,color="r",s=12,linewidth=1.0,linestyle='--',lable=”散点图”)
(3)plt.bar()画条形图
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
三、图画标签添加
1、plt.title()设置画板对象的标签
title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
Parameters ---------- label : str Text to use for the title fontdict : dict A dictionary controlling the appearance of the title text, the default *fontdict* is:: {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight'], 'color': rcParams['axes.titlecolor'], 'verticalalignment': 'baseline', 'horizontalalignment': loc} loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation` Which title to set. y : float, default: :rc:`axes.titley` Vertical Axes loation for the title (1.0 is the top). If None (the default), y is determined automatically to avoid decorators on the Axes. pad : float, default: :rc:`axes.titlepad` The offset of the title from the top of the Axes, in points.
fontsize设置字体大小,默认12,可选参数 ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']
fontweight设置字体粗细,可选参数 ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
fontstyle设置字体类型,可选参数[ 'normal' | 'italic' | 'oblique' ],italic斜体,oblique倾斜
verticalalignment设置水平对齐方式 ,可选参数 : 'center' , 'top' , 'bottom' ,'baseline'
horizontalalignment设置垂直对齐方式,可选参数:left,right,center
rotation(旋转角度)可选参数为:vertical,horizontal 也可以为数字
alpha透明度,参数值0至1之间
backgroundcolor标题背景颜色
bbox给标题增加外框 ,常用参数如下:
boxstyle方框外形
facecolor(简写fc)背景颜色
edgecolor(简写ec)边框线条颜色
edgewidth边框线条大小
import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((1, 3)) plt.ylim((1, 6)) plt.xticks(x,["one","two","three","four"]) plt.yticks(y,["first","second","thrid","fourth"]) font_dict = {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight']} plt.title(label='helloworld',fontdict=font_dict,loc='right') plt.show()
2、plt.legend()使用设置图标签
调用模式有三种
plt.legend()
plt.legend(labels)
plt.legend(handles,labels)
第一种单图模式
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.show()
第二种单图模式
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1,= plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-') plt.legend(labels=['line1']) plt.show()
第三种单图模式
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj= plt.figure(num = 2, figsize=(8, 5)) L1,= plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-') plt.legend(handles=[L1],labels=['line1']) plt.show()
plt.legend(handles, labels)handles参数里的值是个列表,因为plt.plot()本身输出是个列表对象,所以加个逗号,L1就可以表示列表里输出的对象。
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1= plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-') plt.legend(handles=L1,labels='line1') plt.show()
多图模式
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1, = plt.plot(x,y,marker='o',color="green",linewidth=1.0, linestyle='-') L2, = plt.plot(x,z,marker='o',color="red",linewidth=1.0, linestyle='-') plt.legend(handles=[L1,L2],labels=['line1','line2']) plt.show()
plt.legend()其他可选参数如下
loc : str or pair of floats, default: :rc:`legend.loc` ('best' for axes, 'upper right' for figures) The location of the legend. The strings ``'upper left', 'upper right', 'lower left', 'lower right'`` place the legend at the corresponding corner of the axes/figure. The strings ``'upper center', 'lower center', 'center left', 'center right'`` place the legend at the center of the corresponding edge of the axes/figure. The string ``'center'`` places the legend at the center of the axes/figure. The string ``'best'`` places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case *bbox_to_anchor* will be ignored). For back-compatibility, ``'center right'`` (but no other location) can also be spelled ``'right'``, and each "string" locations can also be given as a numeric value: =============== ============= Location String Location Code =============== ============= '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 =============== ============= bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats Box that is used to position the legend in conjunction with *loc*. Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or `figure.bbox` (if `.Figure.legend`). This argument allows arbitrary placement of the legend. Bbox coordinates are interpreted in the coordinate system given by *bbox_transform*, with the default transform Axes or Figure coordinates, depending on which ``legend`` is called. If a 4-tuple or `.BboxBase` is given, then it specifies the bbox ``(x, y, width, height)`` that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure):: loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5) A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used:: loc='upper right', bbox_to_anchor=(0.5, 0.5) ncol : int, default: 1 The number of columns that the legend has. prop : None or `matplotlib.font_manager.FontProperties` or dict The font properties of the legend. If None (default), the current :data:`matplotlib.rcParams` will be used. fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if *prop* is not specified. labelcolor : str or list The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). numpoints : int, default: :rc:`legend.numpoints` The number of marker points in the legend when creating a legend entry for a `.Line2D` (line). scatterpoints : int, default: :rc:`legend.scatterpoints` The number of marker points in the legend when creating a legend entry for a `.PathCollection` (scatter plot). scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]`` The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to ``[0.5]``. markerscale : float, default: :rc:`legend.markerscale` The relative size of legend markers compared with the originally drawn ones. markerfirst : bool, default: True If *True*, legend marker is placed to the left of the legend label. If *False*, legend marker is placed to the right of the legend label. frameon : bool, default: :rc:`legend.frameon` Whether the legend should be drawn on a patch (frame). fancybox : bool, default: :rc:`legend.fancybox` Whether round edges should be enabled around the `~.FancyBboxPatch` which makes up the legend's background. shadow : bool, default: :rc:`legend.shadow` Whether to draw a shadow behind the legend. framealpha : float, default: :rc:`legend.framealpha` The alpha transparency of the legend's background. If *shadow* is activated and *framealpha* is ``None``, the default value is ignored. facecolor : "inherit" or color, default: :rc:`legend.facecolor` The legend's background color. If ``"inherit"``, use :rc:`axes.facecolor`. edgecolor : "inherit" or color, default: :rc:`legend.edgecolor` The legend's background patch edge color. If ``"inherit"``, use take :rc:`axes.edgecolor`. mode : {"expand", None} If *mode* is set to ``"expand"`` the legend will be horizontally expanded to fill the axes area (or *bbox_to_anchor* if defines the legend's size). bbox_transform : None or `matplotlib.transforms.Transform` The transform for the bounding box (*bbox_to_anchor*). For a value of ``None`` (default) the Axes' :data:`~matplotlib.axes.Axes.transAxes` transform will be used. title : str or None The legend's title. Default is no title (``None``). title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize` The font size of the legend's title. borderpad : float, default: :rc:`legend.borderpad` The fractional whitespace inside the legend border, in font-size units. labelspacing : float, default: :rc:`legend.labelspacing` The vertical space between the legend entries, in font-size units. handlelength : float, default: :rc:`legend.handlelength` The length of the legend handles, in font-size units. handletextpad : float, default: :rc:`legend.handletextpad` The pad between the legend handle and text, in font-size units. borderaxespad : float, default: :rc:`legend.borderaxespad` The pad between the axes and legend border, in font-size units. columnspacing : float, default: :rc:`legend.columnspacing` The spacing between columns, in font-size units. handler_map : dict or None The custom dictionary mapping instances or types to a legend handler. This *handler_map* updates the default handler map found at `matplotlib.legend.Legend.get_legend_handler_map`.
3、设置x轴和y轴的标签
plt.xlabel('longitude') #表明x轴标签是longitude
plt.ylabel('latitude') #表明y轴标签是latitude
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1, = plt.plot(x,y,marker='o',color="green",linewidth=1.0, linestyle='-') L2, = plt.plot(x,z,marker='o',color="red",linewidth=1.0, linestyle='-') plt.legend(handles=[L1,L2],labels=['line1','line2']) plt.xlabel('longitude') plt.ylabel('latitude') plt.show()
4、设置图画轴线取值范围
只有一个图需要设置轴线范围的时候
一起设置范围
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.axis([-1,2,1,3]) plt.show()
分别设置范围
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((-1, 2)) plt.ylim((1, 3)) plt.show()
多个图需要设置轴线范围的时候
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1, = plt.plot(x,y,marker='o',color="green",linewidth=1.0, linestyle='-') L2, = plt.plot(x,z,marker='o',color="red",linewidth=1.0, linestyle='-') plt.legend(handles=[L1,L2],labels=['line1','line2']) plt.xlabel('longitude') plt.ylabel('latitude') L1.set_xdata((-1, 2)) L1.set_ydata((1, 3)) L2.set_xdata((1,3)) L2.set_ydata((1, 10)) plt.show()
5、设置画图轴线点位置的标签
plt.xticks(x,["one","two","three","four"])
plt.yticks(y,["first","second","thrid","fourth"])
# 第一个参数是点的位置,第二个参数是对应点的标签。
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((1, 3)) plt.ylim((1, 6)) plt.xticks(x,["one","two","three","four"]) plt.yticks(y,["first","second","thrid","fourth"]) plt.show()
6、设置边框颜色
import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((1, 3)) plt.ylim((1, 6)) font_dict = {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight']} plt.title(label='helloworld',fontdict=font_dict,loc='right') ax = plt.gca() ax.spines['right'].set_color('red') #把右边框设置为红色 ax.spines['top'].set_color('red') #把顶边框设置为红色 plt.show()
7、设置边框绑定x轴和y轴
import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((1, 3)) plt.ylim((1, 6)) font_dict = {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight']} plt.title(label='helloworld',fontdict=font_dict,loc='right') ax = plt.gca() ax.spines['right'].set_color('red') #把右边框设置为红色 ax.spines['top'].set_color('red') #把顶边框设置为红色 ax.xaxis.set_ticks_position('top') #把x轴绑定在顶边框 ax.yaxis.set_ticks_position('right') #把y轴绑定在右边边框 plt.show()
8、设置边框位置
import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((1, 3)) plt.ylim((1, 6)) font_dict = {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight']} plt.title(label='helloworld',fontdict=font_dict,loc='right') ax = plt.gca() right_frame = ax.spines['right'] #创建右边框对象 right_frame.set_color('red') #设置右边框为红色 top_frame = ax.spines['top'] #创建顶边框对象 top_frame.set_color('red') #设置顶边框为红色 right_frame.set_position(('data', 0)) #设置边框位置 top_frame.set_position(('data', 0)) #设置边框位置 x_axis = ax.xaxis #创建x轴对象 x_axis.set_ticks_position('top') #把x轴对象设置到顶端边框 y_axis = ax.yaxis #创建y轴对象 y_axis.set_ticks_position('right') #把y轴对象设置到右端边框 plt.show()
边框位置设置参数说明
Help on method set_position in module matplotlib.spines: set_position(position) method of matplotlib.spines.Spine instance Set the position of the spine. Spine position is specified by a 2 tuple of (position type, amount). The position types are: * 'outward': place the spine out from the data area by the specified number of points. (Negative values place the spine inwards.) * 'axes': place the spine at the specified Axes coordinate (0 to 1). * 'data': place the spine at the specified data coordinate. Additionally, shorthand notations define a special positions: * 'center' -> ('axes', 0.5) * 'zero' -> ('data', 0.0)
9、设置关键点的注释
(1)annotate(text, xy, *args, **kwargs)
text 为注释文本内容
xy 为被注释的坐标点,例如(3,3)
xytext 为注释文字的坐标位置,例如(3,2.7)
import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((1, 3)) plt.ylim((1, 6)) font_dict = {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight']} plt.title(label='helloworld',fontdict=font_dict,loc='right') ax = plt.gca() right_frame = ax.spines['right'] #创建右边框对象 right_frame.set_color('red') #设置右边框为红色 top_frame = ax.spines['top'] #创建顶边框对象 top_frame.set_color('red') #设置顶边框为红色 x_axis = ax.xaxis #创建x轴对象 x_axis.set_ticks_position('top') #把x轴对象设置到顶端边框 y_axis = ax.yaxis #创建y轴对象 y_axis.set_ticks_position('right') #把y轴对象设置到右端边框 plt.annotate(text="hey",xy=(2,2),xytext=(2,3.7)) plt.show()
详细参数说明如下:
Help on function annotate in module matplotlib.pyplot: annotate(text, xy, *args, **kwargs) Annotate the point *xy* with text *text*. In the simplest form, the text is placed at *xy*. Optionally, the text can be displayed in another position *xytext*. An arrow pointing from the text to the annotated point *xy* can then be added by defining *arrowprops*. Parameters ---------- text : str The text of the annotation. xy : (float, float) The point *(x, y)* to annotate. The coordinate system is determined by *xycoords*. xytext : (float, float), default: *xy* The position *(x, y)* to place the text at. The coordinate system is determined by *textcoords*. xycoords : str or `.Artist` or `.Transform` or callable or (float, float), default: 'data' The coordinate system that *xy* is given in. The following types of values are supported: - One of the following strings: ==================== ============================================ 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 ==================== ============================================ Note that 'subfigure pixels' and 'figure pixels' are the same for the parent figure, so users who want code that is usable in a subfigure can use 'subfigure pixels'. - An `.Artist`: *xy* is interpreted as a fraction of the artist's `~matplotlib.transforms.Bbox`. E.g. *(0, 0)* would be the lower left corner of the bounding box and *(0.5, 1)* would be the center top of the bounding box. - A `.Transform` to transform *xy* to screen coordinates. - A function with one of the following signatures:: def transform(renderer) -> Bbox def transform(renderer) -> Transform where *renderer* is a `.RendererBase` subclass. The result of the function is interpreted like the `.Artist` and `.Transform` cases above. - A tuple *(xcoords, ycoords)* specifying separate coordinate systems for *x* and *y*. *xcoords* and *ycoords* must each be of one of the above described types. See :ref:`plotting-guide-annotation` for more details. textcoords : str or `.Artist` or `.Transform` or callable or (float, float), default: value of *xycoords* The coordinate system that *xytext* is given in. All *xycoords* values are valid as well as the following strings: ================= ========================================= Value Description ================= ========================================= 'offset points' Offset (in points) from the *xy* value 'offset pixels' Offset (in pixels) from the *xy* value ================= ========================================= arrowprops : dict, optional The properties used to draw a `.FancyArrowPatch` arrow between the positions *xy* and *xytext*. Note that the edge of the arrow pointing to *xytext* will be centered on the text itself and may not point directly to the coordinates given in *xytext*. If *arrowprops* does not contain the key 'arrowstyle' the allowed keys are: ========== ====================================================== Key Description ========== ====================================================== width The width of the arrow in points headwidth The width of the base of the arrow head in points headlength The length of the arrow head in points shrink Fraction of total length to shrink from both ends ? Any key to :class:`matplotlib.patches.FancyArrowPatch` ========== ====================================================== If *arrowprops* contains the key 'arrowstyle' the above keys are forbidden. The allowed values of ``'arrowstyle'`` are: ============ ============================================= Name Attrs ============ ============================================= ``'-'`` None ``'->'`` head_length=0.4,head_width=0.2 ``'-['`` widthB=1.0,lengthB=0.2,angleB=None ``'|-|'`` widthA=1.0,widthB=1.0 ``'-|>'`` head_length=0.4,head_width=0.2 ``'<-'`` head_length=0.4,head_width=0.2 ``'<->'`` head_length=0.4,head_width=0.2 ``'<|-'`` head_length=0.4,head_width=0.2 ``'<|-|>'`` head_length=0.4,head_width=0.2 ``'fancy'`` head_length=0.4,head_width=0.4,tail_width=0.4 ``'simple'`` head_length=0.5,head_width=0.5,tail_width=0.2 ``'wedge'`` tail_width=0.3,shrink_factor=0.5 ============ ============================================= Valid keys for `~matplotlib.patches.FancyArrowPatch` are: =============== ================================================== Key Description =============== ================================================== arrowstyle the arrow style connectionstyle the connection style relpos default is (0.5, 0.5) patchA default is bounding box of the text patchB default is None shrinkA default is 2 points shrinkB default is 2 points mutation_scale default is text size (in points) mutation_aspect default is 1. ? any key for :class:`matplotlib.patches.PathPatch` =============== ================================================== Defaults to None, i.e. no arrow is drawn. annotation_clip : bool or None, default: None Whether to draw the annotation when the annotation point *xy* is outside the axes area. - If *True*, the annotation will only be drawn when *xy* is within the axes. - If *False*, the annotation will always be drawn. - If *None*, the annotation will only be drawn when *xy* is within the axes and *xycoords* is 'data'. **kwargs Additional kwargs are passed to `~matplotlib.text.Text`. Returns ------- `.Annotation` See Also -------- :ref:`plotting-guide-annotation`
(2)text(x, y, s, fontdict=None, **kwargs)
x,y:表示坐标值上的值
s:表示说明文字,字符串格式
fontsize:表示字体大小
verticalalignment:垂直对齐方式 ,参数:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
horizontalalignment:水平对齐方式 ,参数:[ ‘center’ | ‘right’ | ‘left’ ]
import matplotlib.pyplot as plt import numpy as np from matplotlib import rcParams x=np.array([1,2,3,4,]) y=x*2 z= x*4 obj = plt.figure(num = 2, figsize=(8, 5)) L1 = plt.plot(x,y,marker='o',color="#008000",linewidth=1.0, linestyle='-', label='line1') plt.legend() plt.xlim((1, 3)) plt.ylim((1, 6)) font_dict = {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight']} plt.title(label='helloworld',fontdict=font_dict,loc='right') ax = plt.gca() right_frame = ax.spines['right'] #创建右边框对象 right_frame.set_color('red') #设置右边框为红色 top_frame = ax.spines['top'] #创建顶边框对象 top_frame.set_color('red') #设置顶边框为红色 plt.text(2, 4, 'KK', fontsize=12) plt.show()
详细参数说明如下:
Help on function text in module matplotlib.pyplot: text(x, y, s, fontdict=None, **kwargs) Add text to the Axes. Add the text *s* to the Axes at location *x*, *y* in data coordinates. Parameters ---------- x, y : float The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the *transform* parameter. s : str The text. fontdict : dict, default: None A dictionary to override the default text properties. If fontdict is None, the defaults are determined by `.rcParams`. Returns ------- `.Text` The created `.Text` instance. Other Parameters ---------------- **kwargs : `~matplotlib.text.Text` properties. Other miscellaneous text parameters. Properties: 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 backgroundcolor: color bbox: dict with properties for `.patches.FancyBboxPatch` clip_box: `.Bbox` clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown figure: `.Figure` fontfamily or family: {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} fontproperties or font or font_properties: `.font_manager.FontProperties` or `str` or `pathlib.Path` fontsize or size: float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} fontstretch or stretch: {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'} fontstyle or style: {'normal', 'italic', 'oblique'} fontvariant or variant: {'normal', 'small-caps'} fontweight or weight: {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'} gid: str horizontalalignment or ha: {'center', 'right', 'left'} in_layout: bool label: object linespacing: float (multiple of font size) math_fontfamily: str multialignment or ma: {'left', 'right', 'center'} path_effects: `.AbstractPathEffect` picker: None or bool or float or callable position: (float, float) rasterized: bool rotation: float or {'vertical', 'horizontal'} rotation_mode: {None, 'default', 'anchor'} sketch_params: (scale: float, length: float, randomness: float) snap: bool or None text: object transform: `.Transform` transform_rotates_text: bool url: str usetex: bool or None verticalalignment or va: {'center', 'top', 'bottom', 'baseline', 'center_baseline'} visible: bool wrap: bool x: float y: float zorder: float Examples -------- Individual keyword arguments can be used to override any given parameter:: >>> text(x, y, s, fontsize=12) The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords ((0, 0) is lower-left and (1, 1) is upper-right). The example below places text in the center of the Axes:: >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center', ... verticalalignment='center', transform=ax.transAxes) You can put a rectangular box around the text instance (e.g., to set a background color) by using the keyword *bbox*. *bbox* is a dictionary of `~matplotlib.patches.Rectangle` properties. For example:: >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
四、子图
Matplotlib 里的常用类的包含关系为 Figure -> Axes -> (Line2D, Text, etc.)一个Figure对象可以包含多个子图(Axes),在matplotlib中用Axes对象表示一个绘图区域,可以理解为子图。
面向对象画图:matplotlib API包含有三层,Artist层处理所有的高层结构,例如处理图表、文字和曲线等的绘制和布局。通常我们只和Artist打交道,而不需要关心底层的绘制细节。
import matplotlib.pyplot as plt X1 = range(0, 50) Y1 = [num**2 for num in X1] # y = x^2 X2 = [0, 1] Y2 = [0, 1] # y = x Fig = plt.figure(figsize=(8,4)) # Create a `figure' instance Ax = Fig.add_subplot(111) # Create a `axes' instance in the figure Ax.plot(X1, Y1, X2, Y2) # Create a Line2D instance in the axes Fig.show() Fig.savefig("test.pdf")
1、构造子图方式:Figure.add_axes
add_axes为新增子区域,该区域可以座落在figure内任意位置,且该区域可任意设置大小
import numpy as np import matplotlib.pyplot as plt #新建figure fig = plt.figure() # 定义数据 x = [1, 2, 3, 4, 5, 6, 7] y = [1, 3, 4, 2, 5, 8, 6] #新建区域ax1 #figure的百分比,从figure 10%的位置开始绘制, 宽高是figure的80% left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 # 获得绘制的句柄 ax1 = fig.add_axes([left, bottom, width, height]) ax1.plot(x, y, 'r') ax1.set_title('area1') #新增区域ax2,嵌套在ax1内 left, bottom, width, height = 0.2, 0.6, 0.25, 0.25 # 获得绘制的句柄 ax2 = fig.add_axes([left, bottom, width, height]) ax2.plot(x, y, 'b') ax2.set_title('area2') plt.show()
2、构造子图方式Figure.add_subplot
add_subplot是面对象figure类api,pyplot api中没有此命令
add_subplot的参数与subplots的相似
import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 100) #新建figure对象 fig=plt.figure() #新建子图1 ax1=fig.add_subplot(2,2,1) ax1.plot(x, x) #新建子图3 ax3=fig.add_subplot(2,2,3) ax3.plot(x, x ** 2) ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3) #新建子图4 ax4=fig.add_subplot(2,2,4) ax4.plot(x, np.log(x)) plt.show()
3、构造子图方式:Figure.subplots
4、构造子图方式:pyplot.subplot
可以使用subplot()快速绘制包含多个子图的图表,它的调用形式如下:
subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(**kwargs) subplot(ax)
subplot(numRows, numCols, plotNum)
subplot将整个绘图区域等分为numRows行* numCols列个子区域,然后按照从左到右,
从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1。如果numRows,numCols和plotNum这三个数都小于10的话,可以把它们缩写为一个整数,例如subplot(323)和subplot(3,2,3)是相同的。subplot在plotNum指定的区域中创建一个轴对象。如果新创建的轴和之前创建的轴重叠的话,之前的轴将被删除。
subplot()返回它所创建的Axes对象,我们可以将它用变量保存起来,然后用sca()交替让它们成为当前Axes对象,并调用plot()在其中绘图。
import numpy as np import matplotlib.pyplot as plt plt.figure(1) # 创建图表1 plt.figure(2) # 创建图表2 ax1 = plt.subplot(211) # 在图表2中创建子图1 ax2 = plt.subplot(212) # 在图表2中创建子图2 x = np.linspace(0, 3, 100) for i in range(5): plt.figure(1) #选择图表1 plt.plot(x, np.exp(i*x/3)) plt.sca(ax1) #选择图表2的子图1 plt.plot(x, np.sin(i*x)) plt.sca(ax2) # 选择图表2的子图2 plt.plot(x, np.cos(i*x)) plt.show()
5、构造子图方式: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参数:int类型,默认都为1。
sharex, sharey参数:bool值,默认为False,也可以取值{'none', 'all', 'row', 'col'}的其中一个。
True or 'all': 所有子区域共享同一个x轴和y轴。
False or 'none': 每个子区域的坐标轴都是独立的。
'row': 同一行的子区域共享坐标轴。
'col': 同一列的子区域共享坐标轴。
squeeze:bool值,默认True。
subplot_kw: dict, optional。字典关键字可以通过add_subplot的调用创建子区域。
gridspec_kw:dict, optional。字典关键字可以通过GridSpec构造器的调用创建子网格区域。
**fig_kw:更多的参数可以pyplot.figure对象调用。
返回值:有两个
fig:Figure对象
ax:axes.Axes
对象或者array of Axes
import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 100) #划分子图 fig,axes=plt.subplots(2,2) ax1=axes[0,0] ax2=axes[0,1] ax3=axes[1,0] ax4=axes[1,1] #子图1 ax1.plot(x, x) #子图2 ax2.plot(x, -x) #子图3 ax3.plot(x, x ** 2) ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3) #子图4 ax4.plot(x, np.log(x)) plt.show()
6、设置中文显示
matplotlib模块默认没有显示中文字体的文件,所以得复制一些字体文件到其字体设置目录里。
>>> import matplotlib >>> print(matplotlib.matplotlib_fname()) /root/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc >>> [root@localhost fonts]# cd /usr/local/conda/pkgs/matplotlib-base-3.4.2-py38hab158f2_0/lib/python3.8/site-packages/matplotlib/mpl-data [root@localhost mpl-data]# cd fonts/ttf/ #把想要设置中文显示得字体文件复制到此目录下。字体文件可以从windows系统下这个路径查找:C:\Windows\Fonts >>> from matplotlib import font_manager >>> font_manager.fontManager.addfont("/root/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf") >>> font_manager.fontManager.findfont('simhei') '/root/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf'
(1)FontProperties方法
#coding=utf-8 import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties fig = plt.figure() font = FontProperties(fname="c:\windows\fonts\simsun.ttc", size=14) #fname参数值是字体文件的绝对路径 plt.xlabel(u"x轴", fontproperties=font) plt.show()
(2) rcParams方法
#coding=utf-8 import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties fig = plt.figure() plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.xlabel(u"x轴") plt.show()
(3)rc方法
#coding=utf-8 import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties fig = plt.figure() font = {'family' : 'SimHei','weight' : 'bold','size' : '16'} plt.rc('font', **font) plt.rc('axes', unicode_minus=False) plt.xlabel(u"x轴") plt.show()
方式一用时才设置,且不会污染全局字体设置,更灵活
方式二则设置为全局字体
方式三不需要对字体路径硬编码,而且一次设置,多次使用,更方便。
【附录】 一些中文字体的英文名 宋体 SimSun 黑体 SimHei 微软雅黑 Microsoft YaHei 微软正黑体 Microsoft JhengHei 新宋体 NSimSun 新细明体 PMingLiU 细明体 MingLiU 标楷体 DFKai-SB 仿宋 FangSong 楷体 KaiTi 隶书: LiSu 幼圆: YouYuan 华文细黑:STXihei 华文楷体:STKaiti 华文宋体:STSong 华文中宋:STZhongsong 华文仿宋:STFangsong 方正舒体:FZShuTi 方正姚体:FZYaoti 华文彩云:STCaiyun 华文琥珀:STHupo 华文隶书:STLiti 华文行楷:STXingkai 华文新魏:STXinwei
五、画图方法
1、水平条形图
plt. Barh()
2、直方图
matplotlib.pyplot.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)
3、堆叠图
plt.stackplot()
4、饼图
plt.pie(x, explode=None, labels=None, colors=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0,0), frame=False)
x: 指定绘图的数据 explode:指定饼图某些部分的突出显示,即呈现爆炸式 labels:为饼图添加标签说明,类似于图例说明 colors:指定饼图的填充色 autopct:设置百分比格式,如'%.1f%%'为保留一位小数 shadow:是否添加饼图的阴影效果 pctdistance:设置百分比标签与圆心的距离 labeldistance:设置各扇形标签(图例)与圆心的距离; startangle:设置饼图的初始摆放角度, 180为水平; radius:设置饼图的半径大小; counterclock:是否让饼图按逆时针顺序呈现, True / False; wedgeprops:设置饼图内外边界的属性,如边界线的粗细、颜色等, 如wedgeprops = {'linewidth': 1.5, 'edgecolor':'green'} textprops:设置饼图中文本的属性,如字体大小、颜色等; center:指定饼图的中心点位置,默认为原点 frame:是否要显示饼图背后的图框,如果设置为True的话,需要同时控制图框x轴、y轴的范围和饼图的中心位置;
5、 箱线图
plt.boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None)
x:指定要绘制箱线图的数据; notch:是否是凹口的形式展现箱线图,默认非凹口; sym:指定异常点的形状,默认为+号显示; vert:是否需要将箱线图垂直摆放,默认垂直摆放; whis:指定上下须与上下四分位的距离,默认为1.5倍的四分位差; positions:指定箱线图的位置,默认为[0,1,2…]; widths:指定箱线图的宽度,默认为0.5; patch_artist:是否填充箱体的颜色; meanline:是否用线的形式表示均值,默认用点来表示; showmeans:是否显示均值,默认不显示; showcaps:是否显示箱线图顶端和末端的两条线,默认显示; showbox:是否显示箱线图的箱体,默认显示; showfliers:是否显示异常值,默认显示; boxprops:设置箱体的属性,如边框色,填充色等; labels:为箱线图添加标签,类似于图例的作用; filerprops:设置异常值的属性,如异常点的形状、大小、填充色等; medianprops:设置中位数的属性,如线的类型、粗细等; meanprops:设置均值的属性,如点的大小、颜色等; capprops:设置箱线图顶端和末端线条的属性,如颜色、粗细等; whiskerprops:设置须的属性,如颜色、粗细、线的类型等;
6、 等高线图
plt. Clabel()
7、动态图
(1)范例
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() xdata, ydata = [], [] ln, = ax.plot([], [], 'r-', animated=False) def init(): ax.set_xlim(0, 2*np.pi) ax.set_ylim(-1, 1) return ln, def update(frame): xdata.append(frame) ydata.append(np.sin(frame)) ln.set_data(xdata, ydata) return ln, ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),init_func=init, blit=True) plt.show() ani.save('test_animation.gif',writer='imagemagick')
(2)构造函数
我们先来看看 FuncAnimation 的构造方法。
def __init__(self, fig, func, frames=None, init_func=None, fargs=None,save_count=None, **kwargs):
fig: 自然是 matplotlib 中的 figure 对象。
func: 是每一次更新时所调用的方法,它是回调函数。因此,我们可以在这个方法中更新 figure 当中的 axes 中的 line2D 对象,它是动态更新 figure 的根本。
frames : 代表了整个动画过程中帧的取值范围,而本质上是一个数据发生器。
init_func: 是初始函数,用来初始 figure 的画面。
fargs: 是每次附加给 func 回调函数的参数,可以为 None
save_count : 是缓存的数量
除此之外,还有一些可选的参数,它们分别是:
interval: 是每 2 个 frame 发生的时间间隔,单位是 ms,默认值是 200.
repeat_delay: 取值是数值,如果 animation 是重复播放的话,这个值就是每次播放之间的延迟时间,单位是 ms。
repeat bool: 型可选参数,默认为 True,代表动画是否会重复执行
blit bool: 型可选参数,控制绘制的优化。默认是 False。
(3)着重参数分析
animation 的核心参数是 frames 和 func。
frames 可以取值:iterable,int,generator 生成器函数 或者是 None。
但有个前提是,生成器要符合下面的签名格式。
def gen_function() -> obj
func 是回调函数,它会在每次更新的时候被调用,所以我们只需要在这个函数中更新 figure 中的数值就可以了。
实际上,frames 决定了整个动画 frame 的取值范围,它会在 interval 时间内迭代一次,然后将值传递给 func,直到整个 frames 迭代完毕。
(4) 保存动画
ani.save('test_animation.gif',writer='imagemagick')
需要注意到的是,如果要保存 gif 图像,这要求开发者电脑已经安装了 ImageMagicK。
动画可以保存为 gif 图像,自然也能保存为 mp4 视频格式,但这要求开发者计算机已经安装好 ffmpeg 库,并且 save 方法中指定 writer 为 ffmpeg。
六、Artist
基本上,你能在图形上看到的一切都是artist (甚至是图、轴域和轴对象),这包括文本对象、Line2D对象、集合对象、补丁对象…(你明白了)当图被描绘时,所有的artist 都被画在画布上。大多数 artist 都被绑在一个 axes 上,这样的 artist 不能被多个轴共享,也不能从一个轴移动到另一个轴。
利用Artist对象进行绘图的流程分为如下三步
创建Figure对象
为Figure对象创建一个或多个Axes对象
调用Axes对象的方法来创建各种简单的Artist对象