10.2.plot
plot
plot
plt.plot - 绘制折线图或散点图
plt.plot(args, scalex=True, scaley=True, data=None, kwargs)
Plot y versus x as lines and/or markers.
使用格式如下,点或线条的坐标系由 x、y 给出。:
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
fmt:该参数是定义 color、marker、linestyle 的便捷方式,它使用字符串作为值。例子如下:plot(x, y, 'bo') # plot x and y using blue circle markers plot(y, 'r+') # ditto, but with red plusses
也可以使用
.Line2D属性作为关键字参数来更好地控制外观。Line properties 和 fmt 可以混合使用:plot(x, y, 'go--', linewidth=2, markersize=12) plot(x, y, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=12)Line properties 与 fmt 冲突时,关键字参数优先。
color/c:str;线条颜色。linestyle/ls:str;线条样式。linewidth/lw:float;线条宽度。alpha:float;0-1比例的透明度。label:str;图例。dash_capstyle:str;['butt' | 'round' | 'projecting']。虚线的端点样式。dash_joinstyle:str;['miter' | 'round' | 'bevel']。虚线的连接样式。solid_capstyle:str;['butt' | 'round' | 'projecting']。实线的端点样式。-
solid_joinstyle:str;['miter' | 'round' | 'bevel']。实线的连接样式。 -
marker:str;marker的样式。 markersize/ms:marker的大小。fillstyle:str;['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']。marker背景色的填充位置。markeredgecolor/mec:marker的背景边缘颜色。markeredgewidth/mew:float;marker的宽度。markerfacecolor/mfc:marker的背景填充区域的颜色。markerfacecoloralt/mfcalt:marker的背景非填充区域的颜色,填充区域由fillstyle决定。visible:bool;Line2D是否可见。
plt.scatter - 绘制散点图
plt.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None,
verts=<deprecated parameter>, edgecolors=None,
plotnonfinite=False, data=None, kwargs)
plt.xlabel - 设置 X 轴标签
plt.xlabel(xlabel, fontdict=None, labelpad=None, loc=None, kwargs)
loc: {'left', 'center', 'right'}, default::rc:xaxis.labellocation
plt.ylabel - 设置 Y 轴标签
plt.ylabel(ylabel, fontdict=None, labelpad=None, loc=None, kwargs)
loc: {'left', 'center', 'right'}, default::rc:yaxis.labellocation
plt.xlim - 设置/获取 X 轴范围
plt.xlim(*args, **kwargs)
xlim(left, right): set the xlim to left, right
left, right = xlim(): return the current xlim
plt.ylim - 设置/获取 Y 轴范围
plt.ylim(*args, **kwargs)
ylim(bottom, top): set the ylim to bottom, top
bottom, top = ylim(): return the current ylim
plt.xticks - 设置/获取 X 轴刻度的标签
plt.xticks(ticks=None, labels=None, kwargs)
xticks(np.arange(3), ['Tom', 'Dick', 'Sue'], rotation=20): Set text labels and properties.
xticks([]): Disable xticks.
locs, labels = xticks(): Get the current locations and labels.
plt.yticks - 设置/获取 Y 轴刻度的标签
plt.yticks(ticks=None, labels=None, kwargs)
plt.legend - 设置图例
plt.legend(args, kwargs)
所有 Artist 类的 label 默认值为 None,因此在没有 label 参数的情况下调用 “Axes.legend” 不绘制任何图例。
使用 legend( ) 添加图例有三种方法:
-
如果 artist 对象已经设置了 label 属性,则使用已有的 label。可以在创建 artist 对象时就指定 label,或者调用 artist 对象的方法
Artist.set_labeline, = ax.plot([1, 2, 3], label='Inline label') ax.legend() # Or line.set_label('Label via method') line, = ax.plot([1, 2, 3]) ax.legend() -
只在
legendAPI 标记现有的绘图对象,只传入 label,示例代码如下(可能容易弄错图例的顺序),ax.plot([1, 2, 3]) ax.legend(['A simple line']) # Or plt.plot(x1, y1, "g1", x2, y2, 'r1', x3, y3, "k1") plt.legend(["1","2","3"]) -
只在
legendAPI 标记现有的绘图对象,同时传入 iterable of artists 和 iterable of labels。plt.legend((line1, line2, line3), ('label1', 'label2', 'label3')) plt.legend(handles=(line1, line2, line3), labels=('label1', 'label2', 'label3'))
主要参数有三个:loc、handles、label。
-
loc:int or string or pair of floats;default: 'upper right'. legeng的位置;可用值如下:Location String Location Code Note ================================================ '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 -
handles:包含.Artist类的对象的序列,该参数和labels参数一起使用来控制图例handle的长度和labels的长度必须一致,若不一致,会被截为较短的。 -
label:字符串的序列。
其他参数(不是所有的 artist 对象都可以用 legend 的所有参数)
-
bbox_to_anchor:.BboxBaseor pair of floats. 在bbox_transform坐标系(默认为Axes coordinates)中指定图例的任意位置。例如,将原本放在右上角的图例居中于axes:loc='upper right', bbox_to_anchor=(0.5, 0.5) -
bbox_transform:None or :class:matplotlib.transforms.Transform. 边界框的变换(也就是bbox_to_anchor的坐标系)。 ncol:integer. legend的列数,默认为1。columnspacing:float or None. 列之间的间距。Measured in font-size units. 当参数nol不等于1时起作用。prop:None or :class:matplotlib.font_manager.FontPropertiesor dict. legend的字体属性,如果为None(默认),当前:data:matplotlib.rcParams会被使用。fontsize:int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}. 控制legend的字体大小。若使用数值,则是以 point为单位的绝对大小;若使用 string,则字体大小相对于当前默认字体。该参数在prop参数不指定时起作用。markerscale:None or int or float. legend 图标的相对大小,与原始的图标作比较,默认为 None。markerfirst:bool. 若为 True,则 legend marker 位于 legend label 的左边,默认为 True。numpoints:None or int. legend marker的数量。title:图例的标题。shadow:None or bool. 控制是否在图例后面绘制阴影。Default isNone, which will take the value from:rc:legend.shadow.framealpha:None or float. 图例背景的透明度(包括图例的边框)Default isNone。edgecolor:None or "inherit" or a color spec. 控制图例背景边缘(也就是边框)的颜色。facecolor:None or "inherit" or a color spec. 控制图例的背景颜色。labelspacing:float or None. 图例条目之间的垂直空间(vertical space)。以字体大小单位测量。borderpad:float or None. 图例边框内的小数空白(也就是图例距离边框的距离)。以字体大小单位测量。handletextpad:float or None. legend handle和legend label之间的空白填充。以字体大小单位测量。handlelength:float or None. legend handles的长度(也就是)。以字体大小单位测量。borderaxespad:float or None. The pad between the axes and legend border.Measured in font-size units.
plt.text - 添加文本到 axes
plt.text(x, y, s, fontdict=None, kwargs)
plt.annotate - 在指定点添加注解
plt.annotate(text, xy, args, kwargs)
text:注解的文字,s是该参数已弃用的同义词。xy:(float, float). 标注点的坐标,坐标系取决于xycoords参数。xytext:(float, float). 注解文字的坐标,坐标系取决于textcoords参数。-
xycoords:str or.Artistor.Transformor callable or (float, float), default: 'data'. 以下是可用的参数值:================= ============================================= Value Description ================= ============================================= 'figure points' 以 figure 左下角为原点, 以 point 为单位 'figure pixels' 以 figure 左下角为原点, 以 pixel 为单位 'figure fraction' 以 figure 左下角为原点, 以 fraction 为单位, 0,0 左下角; 1,1 右上角 'axes points' 以 axes 左下角为原点, 以 point 为单位 'axes pixels' 以 axes 左下角为原点, 以 pixel 为单位 'axes fraction' 以 axes 左下角为原点, 以 fraction 为单位;0,0 左下角; 1,1 右上角 'data' 使用数据的坐标系, 以数据坐标系的单位为单位. 默认值 'polar' *(theta, r)* 极坐标系, 例如 (np.pi/2,3) ================= ============================================= -
textcoords:str or.Artistor.Transformor callable or (float, float), default: value of xycoords. 注解文本的坐标系。xycoords的可选值都可以用在textcoords中。另外textcoords还多出以下两个参数,当且仅当textcoords默认使用xycoords的坐标系时生效。================= ========================================= Value Description ================= ========================================= 'offset points' 偏移 *xy* 的量, 以 point 为单位 'offset pixels' 偏移 *xy* 的量, 以 pixels 为单位 ================= ========================================= -
annotation_clip:bool. 当注释超出轴区域时,控制注释的可见性。若为 True,则只有当xy位于轴内时才会绘制注释。若为 False,将始终绘制注释。默认值为 None,仅当xycoords='data'时才 True。 -
arrowprops:dict, optional. 设置xy与xytext之间的箭头形状。箭头的类型是~matplotlib.patches.FancyArrowPatch。不同的箭头形状有不同的属性。- 若
arrowwprops=None,则不绘制箭头。 -
如果
arrowprops不包含'arrowstyle'这个key,那么arrowprops中允许存在的key包括:========== ====================================================== Key Description ========== ====================================================== width 箭头(箭头线)的宽度, 以 point 为单位 headwidth 箭头端底部的宽度, 以 point 为单位 headlength 箭头端的长度, 以 point 为单位 shrink 从箭头端到非箭头端收缩的比率 (fraction), 收缩的部分不显示 ? Any key to :class:`matplotlib.patches.FancyArrowPatch` ========== ====================================================== -
如果
arrowprops包含'arrowstyle'这个key,那么以上的 key 会被禁止,允许存在的 key 包括:=============== ================================================== Key Description =============== ================================================== arrowstyle 箭头的样式 connectionstyle 两端连接路径的样式 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` =============== =================================================='arrowstyle'允许的值如下(其中 name 为风格名称,attrs 为可设置的属性):fancy、simple、wedge 仅适用于生成二次样条线段的连接样式。对于这些箭头样式,必须使用 angle3 或 arc3 连接样式。============ ============================================= 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 ============ =============================================
'connectionstyle'允许的值如下:注意,============ ============================================= Name Attrs ============ ============================================= 'angle' angleA=90,angleB=0,rad=0.0 'angle3' angleA=90,angleB=0 'arc' angleA=0,angleB=0,armA=None,armB=None,rad=0.0 'arc3' rad=0.0 ============ =============================================angle3和arc3中的3意味着所得到的路径是二次样条段(三个控制点)。 如下面将讨论的,当连接路径是二次样条时,可以使用一些箭头样式选项。
- 若
# help(plt.plot)
# help(plt.annotate)