- 导入
import matplotlib.pyplot as plt导入
- 文本注释
matplotlib.pyplot.annotate(text, xy, *args, **kwargs)
数据:
text str
指定注释点的位置:
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'
指定箭头的属性:
arrowprops dict, optional
- 增加单个子图
matplotlib.pyplot.subplot(*args, **kwargs)
指定位置:
*args int, (int, int, index), or SubplotSpec
, default: (1, 1, 1)
指定行,列及其索引位置
此处的行,列,索引都是从1开始的
共享轴:
sharex, sharey Axes
, optional
Share the x or y axis
with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
设置标签:
label str
A label for the returned axes.
- 创建包含多个子图的图像(用作第一步)
matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
注意其会返回图像及子图组,使用两个变量来接收
指定行上和列上的子图数量:
nrows, ncols int, default: 1
Number of rows/columns of the subplot grid.
指定是否共享轴:
sharex, sharey bool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of properties among x (sharex) or y (sharey) axes:
- True or 'all': x- or y-axis will be shared among all subplots.
- False or 'none': each subplot x- or y-axis will be independent.
- 'row': each subplot row will share an x- or y-axis.
- 'col': each subplot column will share an x- or y-axis.
fig,ax = plt.subplots()
ax[1,2]可以索引到子图,然后对其进行操作
ax[1,2].set_xlabel()
使用plt.set_xlabel()可以对fig进行设置
- 创建包含多个图像(不是子图)的变量(用作第一步)
plt.figure.add_axes(rect, projection=None, polar=False, **kwargs) # 此处使用的是fig对象对应的方法
rect sequence of float
新轴的尺寸,也就是指定图像的尺寸(为figsize的百分比),分别为 [left, bottom, width, height]
projection {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
指定投影的方式,无则是直线型投影
polar bool, default: False
和projecttion=polar效果一致
sharex, sharey Axes
, optional
共享x轴和y轴
label str
轴的标签
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')
此处axes对应的就是一个轴对象,可以对其进行一些设置,和之前的fig设置相同
- 对当前图像的基本信息进行设置
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)
num int or str, optional
图标的唯一标识符,如果没有标识符,则新建一个图片
figsize (float, float)
单位为英寸,宽度和高度构成的元组
dpi float
facecolor color
图片的背景颜色
edgecolor color
图片的边框颜色
- 对图片进行全局设置
通常使用plt.rc对某一个图片属性进行复制
plt.rc('patch',force_edgecolor=True) # 如上,就对全局的patch的force_edgecolor属性设置为True # 也可以使用如下方式 plt.rcParams["patch.force_edgecolor"] = True # 这是较老的表现形式,其没有实现分组,而是直接引用
rc包含了以下属性(注意其以分组的形式进行展现,所以推荐使用rc函数的形式)
lines相关的
## for more information on line properties. #lines.linewidth: 1.5 # line width in points #lines.linestyle: - # solid line #lines.color: C0 # has no affect on plot(); see axes.prop_cycle #lines.marker: None # the default marker #lines.markerfacecolor: auto # the default marker face color #lines.markeredgecolor: auto # the default marker edge color #lines.markeredgewidth: 1.0 # the line width around the marker symbol #lines.markersize: 6 # marker size, in points #lines.dash_joinstyle: round # {miter, round, bevel} #lines.dash_capstyle: butt # {butt, round, projecting} #lines.solid_joinstyle: round # {miter, round, bevel} #lines.solid_capstyle: projecting # {butt, round, projecting} #lines.antialiased: True # render lines in antialiased (no jaggies)
patches相关的
## Patches are graphical objects that fill 2D space, like polygons or circles. ## See https://matplotlib.org/api/artist_api.html#module-matplotlib.patches ## for more information on patch properties. #patch.linewidth: 1 # edge width in points. #patch.facecolor: C0 #patch.edgecolor: black # if forced, or patch is not filled #patch.force_edgecolor: False # True to always use edgecolor #patch.antialiased: True # render patches in antialiased (no jaggies)
hatches相关的
## * HATCHES * ## *************************************************************************** #hatch.color: black #hatch.linewidth: 1.0
boxplot相关的
## *************************************************************************** #boxplot.notch: False #boxplot.vertical: True #boxplot.whiskers: 1.5 #boxplot.bootstrap: None #boxplot.patchartist: False #boxplot.showmeans: False #boxplot.showcaps: True #boxplot.showbox: True #boxplot.showfliers: True #boxplot.meanline: False #boxplot.flierprops.color: black #boxplot.flierprops.marker: o #boxplot.flierprops.markerfacecolor: none #boxplot.flierprops.markeredgecolor: black #boxplot.flierprops.markeredgewidth: 1.0 #boxplot.flierprops.markersize: 6 #boxplot.flierprops.linestyle: none #boxplot.flierprops.linewidth: 1.0 #boxplot.boxprops.color: black #boxplot.boxprops.linewidth: 1.0 #boxplot.boxprops.linestyle: - #boxplot.whiskerprops.color: black #boxplot.whiskerprops.linewidth: 1.0 #boxplot.whiskerprops.linestyle: - #boxplot.capprops.color: black #boxplot.capprops.linewidth: 1.0 #boxplot.capprops.linestyle: - #boxplot.medianprops.color: C1 #boxplot.medianprops.linewidth: 1.0 #boxplot.medianprops.linestyle: - #boxplot.meanprops.color: C2 #boxplot.meanprops.marker: ^ #boxplot.meanprops.markerfacecolor: C2 #boxplot.meanprops.markeredgecolor: C2 #boxplot.meanprops.markersize: 6 #boxplot.meanprops.linestyle: -- #boxplot.meanprops.linewidth: 1.0
font相关的
#font.family: sans-serif #font.style: normal #font.variant: normal #font.weight: normal #font.stretch: normal #font.size: 10.0 #font.serif: DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif #font.sans-serif: DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif #font.cursive: Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive #font.fantasy: Comic Neue, Comic Sans MS, Chicago, Charcoal, ImpactWestern, Humor Sans, xkcd, fantasy #font.monospace: DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
text相关的
## for more information on text properties #text.color: black
axes相关的
## https://matplotlib.org/api/axes_api.html#module-matplotlib.axes #axes.facecolor: white # axes background color #axes.edgecolor: black # axes edge color #axes.linewidth: 0.8 # edge linewidth #axes.grid: False # display grid or not #axes.grid.axis: both # which axis the grid should apply to #axes.grid.which: major # gridlines at {major, minor, both} ticks #axes.titlelocation: center # alignment of the title: {left, right, center} #axes.titlesize: large # fontsize of the axes title #axes.titleweight: normal # font weight of title #axes.titlecolor: auto # color of the axes title, auto falls back to # text.color as default value #axes.titley: None # position title (axes relative units). None implies auto #axes.titlepad: 6.0 # pad between axes and title in points #axes.labelsize: medium # fontsize of the x any y labels #axes.labelpad: 4.0 # space between label and axis #axes.labelweight: normal # weight of the x and y labels #axes.labelcolor: black #axes.axisbelow: line # draw axis gridlines and ticks: # - below patches (True) # - above patches but below lines ('line') # - above all (False) #axes.formatter.limits: -5, 6 # use scientific notation if log10 # of the axis range is smaller than the # first or larger than the second #axes.formatter.use_locale: False # When True, format tick labels # according to the user's locale. # For example, use ',' as a decimal # separator in the fr_FR locale. #axes.formatter.use_mathtext: False # When True, use mathtext for scientific # notation. #axes.formatter.min_exponent: 0 # minimum exponent to format in scientific notation #axes.formatter.useoffset: True # If True, the tick label formatter # will default to labeling ticks relative # to an offset when the data range is # small compared to the minimum absolute # value of the data. #axes.formatter.offset_threshold: 4 # When useoffset is True, the offset # will be used when it can remove # at least this number of significant # digits from tick labels. #axes.spines.left: True # display axis spines #axes.spines.bottom: True #axes.spines.top: True #axes.spines.right: True #axes.unicode_minus: True # use Unicode for the minus symbol rather than hyphen. See # https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes #axes.prop_cycle: cycler('color', ['1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf']) # color cycle for plot lines as list of string colorspecs: # single letter, long name, or web-style hex # As opposed to all other paramters in this file, the color # values must be enclosed in quotes for this parameter, # e.g. '1f77b4', instead of 1f77b4. # See also https://matplotlib.org/tutorials/intermediate/color_cycle.html # for more details on prop_cycle usage. #axes.autolimit_mode: data # How to scale axes limits to the data. By using: # - "data" to use data limits, plus some margin # - "round_numbers" move to the nearest "round" number #axes.xmargin: .05 # x margin. See `axes.Axes.margins` #axes.ymargin: .05 # y margin. See `axes.Axes.margins` #polaraxes.grid: True # display grid on polar axes #axes3d.grid: True # display grid on 3d axes
axis相关的
## * AXIS * ## *************************************************************************** #xaxis.labellocation: center # alignment of the xaxis label: {left, right, center} #yaxis.labellocation: center # alignment of the yaxis label: {bottom, top, center}
dates相关的
## These control the default format strings used in AutoDateFormatter. ## Any valid format datetime format string can be used (see the python ## `datetime` for details). For example, by using: ## - '%%x' will use the locale date representation ## - '%%X' will use the locale time representation ## - '%%c' will use the full locale datetime representation ## These values map to the scales: ## {'year': 365, 'month': 30, 'day': 1, 'hour': 1/24, 'minute': 1 / (24 * 60)} #date.autoformatter.year: %Y #date.autoformatter.month: %Y-%m #date.autoformatter.day: %Y-%m-%d #date.autoformatter.hour: %m-%d %H #date.autoformatter.minute: %d %H:%M #date.autoformatter.second: %H:%M:%S #date.autoformatter.microsecond: %M:%S.%f
ticks相关的
## *************************************************************************** ## See https://matplotlib.org/api/axis_api.html#matplotlib.axis.Tick #xtick.top: False # draw ticks on the top side #xtick.bottom: True # draw ticks on the bottom side #xtick.labeltop: False # draw label on the top #xtick.labelbottom: True # draw label on the bottom #xtick.major.size: 3.5 # major tick size in points #xtick.minor.size: 2 # minor tick size in points #xtick.major.width: 0.8 # major tick width in points #xtick.minor.width: 0.6 # minor tick width in points #xtick.major.pad: 3.5 # distance to major tick label in points #xtick.minor.pad: 3.4 # distance to the minor tick label in points #xtick.color: black # color of the tick labels #xtick.labelsize: medium # fontsize of the tick labels #xtick.direction: out # direction: {in, out, inout} #xtick.minor.visible: False # visibility of minor ticks on x-axis #xtick.major.top: True # draw x axis top major ticks #xtick.major.bottom: True # draw x axis bottom major ticks #xtick.minor.top: True # draw x axis top minor ticks #xtick.minor.bottom: True # draw x axis bottom minor ticks #xtick.alignment: center # alignment of xticks #ytick.left: True # draw ticks on the left side #ytick.right: False # draw ticks on the right side #ytick.labelleft: True # draw tick labels on the left side #ytick.labelright: False # draw tick labels on the right side #ytick.major.size: 3.5 # major tick size in points #ytick.minor.size: 2 # minor tick size in points #ytick.major.width: 0.8 # major tick width in points #ytick.minor.width: 0.6 # minor tick width in points #ytick.major.pad: 3.5 # distance to major tick label in points #ytick.minor.pad: 3.4 # distance to the minor tick label in points #ytick.color: black # color of the tick labels #ytick.labelsize: medium # fontsize of the tick labels #ytick.direction: out # direction: {in, out, inout} #ytick.minor.visible: False # visibility of minor ticks on y-axis #ytick.major.left: True # draw y axis left major ticks #ytick.major.right: True # draw y axis right major ticks #ytick.minor.left: True # draw y axis left minor ticks #ytick.minor.right: True # draw y axis right minor ticks #ytick.alignment: center_baseline # alignment of yticks
grids相关的
## * GRIDS * ## *************************************************************************** #grid.color: b0b0b0 # grid color #grid.linestyle: - # solid #grid.linewidth: 0.8 # in points #grid.alpha: 1.0 # transparency, between 0.0 and 1.0
legend相关的
#legend.loc: best #legend.frameon: True # if True, draw the legend on a background patch #legend.framealpha: 0.8 # legend patch transparency #legend.facecolor: inherit # inherit from axes.facecolor; or color spec #legend.edgecolor: 0.8 # background patch boundary color #legend.fancybox: True # if True, use a rounded box for the # legend background, else a rectangle #legend.shadow: False # if True, give background a shadow effect #legend.numpoints: 1 # the number of marker points in the legend line #legend.scatterpoints: 1 # number of scatter points #legend.markerscale: 1.0 # the relative size of legend markers vs. original #legend.fontsize: medium #legend.title_fontsize: None # None sets to the same as the default axes. ## Dimensions as fraction of fontsize: #legend.borderpad: 0.4 # border whitespace #legend.labelspacing: 0.5 # the vertical space between the legend entries #legend.handlelength: 2.0 # the length of the legend lines #legend.handleheight: 0.7 # the height of the legend handle #legend.handletextpad: 0.8 # the space between the legend line and legend text #legend.borderaxespad: 0.5 # the border between the axes and legend edge #legend.columnspacing: 2.0 # column separation
figure相关的
## See https://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure #figure.titlesize: large # size of the figure title (``Figure.suptitle()``) #figure.titleweight: normal # weight of the figure title #figure.figsize: 6.4, 4.8 # figure size in inches #figure.dpi: 100 # figure dots per inch #figure.facecolor: white # figure facecolor #figure.edgecolor: white # figure edgecolor #figure.frameon: True # enable figure frame #figure.max_open_warning: 20 # The maximum number of figures to open through # the pyplot interface before emitting a warning. # If less than one this feature is disabled. #figure.raise_window : True # Raise the GUI window to front when show() is called. ## The figure subplot parameters. All dimensions are a fraction of the figure width and height. #figure.subplot.left: 0.125 # the left side of the subplots of the figure #figure.subplot.right: 0.9 # the right side of the subplots of the figure #figure.subplot.bottom: 0.11 # the bottom of the subplots of the figure #figure.subplot.top: 0.88 # the top of the subplots of the figure #figure.subplot.wspace: 0.2 # the amount of width reserved for space between subplots, # expressed as a fraction of the average axis width #figure.subplot.hspace: 0.2 # the amount of height reserved for space between subplots, # expressed as a fraction of the average axis height ## Figure layout #figure.autolayout: False # When True, automatically adjust subplot # parameters to make the plot fit the figure # using `tight_layout` #figure.constrained_layout.use: False # When True, automatically make plot # elements fit on the figure. (Not # compatible with `autolayout`, above). #figure.constrained_layout.h_pad: 0.04167 # Padding around axes objects. Float representing #figure.constrained_layout.w_pad: 0.04167 # inches. Default is 3./72. inches (3 pts) #figure.constrained_layout.hspace: 0.02 # Space between subplot groups. Float representing #figure.constrained_layout.wspace: 0.02 # a fraction of the subplot widths being separated.
images相关的
#image.aspect: equal # {equal, auto} or a number #image.interpolation: antialiased # see help(imshow) for options #image.cmap: viridis # A colormap name, gray etc... #image.lut: 256 # the size of the colormap lookup table #image.origin: upper # {lower, upper} #image.resample: True #image.composite_image: True # When True, all the images on a set of axes are # combined into a single composite image before # saving a figure as a vector graphics file, # such as a PDF.
saving相关的
## * SAVING FIGURES * ## *************************************************************************** ## The default savefig params can be different from the display params ## e.g., you may want a higher resolution, or to make the figure ## background white #savefig.dpi: figure # figure dots per inch or 'figure' #savefig.facecolor: auto # figure facecolor when saving #savefig.edgecolor: auto # figure edgecolor when saving #savefig.format: png # {png, ps, pdf, svg} #savefig.bbox: standard # {tight, standard} # 'tight' is incompatible with pipe-based animation # backends (e.g. 'ffmpeg') but will work with those # based on temporary files (e.g. 'ffmpeg_file') #savefig.pad_inches: 0.1 # Padding to be used when bbox is set to 'tight' #savefig.directory: ~ # default directory in savefig dialog box, # leave empty to always use current working directory #savefig.transparent: False # setting that controls whether figures are saved with a # transparent background by default #savefig.orientation: portrait # Orientation of saved figure
- 对当前图像的基本信息进行设置
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)
num int or str, optional
图标的唯一标识符,如果没有标识符,则新建一个图片
figsize (float, float)
单位为英寸,宽度和高度构成的元组
dpi float
facecolor color
图片的背景颜色
edgecolor color
图片的边框颜色
- 网格线
matplotlib.pyplot.grid(b=None, which='major', axis='both', **kwargs
b bool or None, optional
是否显示网格线
which {'major', 'minor', 'both'}, optional
主要的网格行
axis {'both', 'x', 'y'}, optional
网格的方向
注意,网格的密度是由横纵坐标上的变量数决定的
如果想要提高密度,可以使用plt.xticks()或者plt.yticks()增加横纵的标签数目
plt.rc('axes', axisbelow=True)
# 将网格始终置于底部
- 标签位置设置
matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
ticks array-like, optional
设置标签的位置,输入一个空序列可以不显示标签
位置的基准是横坐标或者纵坐标索引的值
如果其是字符串索引,则可能无法调整
(非统计型图像,如条形图折线图,最好使用两列数值数据(两个数值点定位一个数据),然后再在ticks上设置数值和表索引的对应关系,这样便于定位)
labels array-like, optional
在指定标签的位置上放置标签,需要首先设置ticks
如果不设置label,其就会直接显示设置的ticks