matplotlib
#
一个面向对象的绘图库。
通过伴随的 pyplot 模块提供了一个过程式接口,该模块可以直接导入,例如:
import matplotlib.pyplot as plt
或使用 ipython:
ipython
在你的终端中,接着输入:
In [1]: %matplotlib
In [2]: import matplotlib.pyplot as plt
在 ipython shell 提示符下。
在大多数情况下,编程时应鼓励直接使用显式的面向对象库;隐式的pyplot接口主要用于交互式工作。这个建议的例外是pyplot函数`.pyplot.figure`、pyplot.subplot
、pyplot.subplots`和
.pyplot.savefig`,它们可以极大地简化脚本编写。有关隐式和显式接口之间权衡的解释,请参见:ref:api_interfaces
。
模块包括:
matplotlib.axes
matplotlib.figure
Figure
类。matplotlib.artist
所有绘制事物的类的
Artist
基类。matplotlib.lines
用于绘制线条和标记的
Line2D
类。matplotlib.patches
用于绘制多边形的类。
matplotlib.text
Text
和Annotation
类。matplotlib.image
AxesImage
和FigureImage
类。matplotlib.collections
用于高效绘制线条或多边形组的类。
matplotlib.colors
颜色规范和创建颜色映射。
matplotlib.cm
颜色映射,以及为其他类提供颜色映射功能的
ScalarMappable
混合类。matplotlib.ticker
计算刻度位置和格式化刻度标签。
matplotlib.backends
一个包含用于各种GUI库和输出格式的模块的子包。
matplotlib 的基础命名空间包括:
rcParams
默认配置设置;它们的默认值可以通过
matplotlibrc
文件覆盖。use
设置 Matplotlib 后端。 这应该在创建任何图形之前调用,因为在那之后无法在不同的 GUI 后端之间切换。
可以使用以下环境变量来自定义行为:
MPLBACKEND
这个可选变量可以设置为选择 Matplotlib 的后端。参见 什么是后端?。
MPLCONFIGDIR
这是用于存储用户对 Matplotlib 的自定义设置的目录,以及一些用于提高性能的缓存。如果未定义
MPLCONFIGDIR
,则在 Linux 上使用HOME/.config/matplotlib
和HOME/.cache/matplotlib
,在其他平台上使用HOME/.matplotlib`(如果它们可写)。否则,使用 Python 标准库的 `tempfile.gettempdir
来查找一个基本目录,在其中创建matplotlib
子目录。
Matplotlib 最初由 John D. Hunter (1968-2012) 编写,现在由众多开发者维护。
偶尔,内部文档(Python 文档字符串)会提及 MATLAB®,这是 The MathWorks, Inc. 的注册商标。
后台管理#
- matplotlib.use(backend, *, force=True)[源代码][源代码]#
选择用于渲染和GUI集成的后端。
如果已经导入了 pyplot,则使用
switch_backend
,如果新后端与当前后端不同,所有图形将被关闭。- 参数:
- 后端str
要切换到的后端。这可以是标准后端名称之一,这些名称不区分大小写:
交互式后端:GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg, QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo
非交互式后端:agg, cairo, pdf, pgf, ps, svg, template
或一个形式为
module://my.module.name
的字符串。notebook 是 nbAgg 的同义词。
如果已经启动了一个不相关的事件循环(例如,如果已经打开了一个 TkAgg 窗口,则无法切换到 GTK3Agg),则无法切换到交互式后端。切换到非交互式后端始终是可能的。
- 强制bool, 默认值: True
如果为 True(默认值),当无法设置后端时(可能是因为导入失败,或因为已经运行了一个不兼容的 GUI 交互框架),引发一个
ImportError
;如果为 False,则静默忽略失败。
- matplotlib.interactive(b)[源代码][源代码]#
设置是否在每次绘图命令后重绘(例如
pyplot.xlabel
)。
- matplotlib.is_interactive()[源代码][源代码]#
返回是否在每次绘图命令后重绘。
备注
此函数仅用于后端使用。终端用户应使用
pyplot.isinteractive
代替。
默认值和样式#
- class matplotlib.RcParams(*args, **kwargs)[源代码][源代码]#
一个类似字典的键值存储,用于配置参数,包括验证。
验证函数在
matplotlib.rcsetup
中定义并与 rc 参数关联。rcParams 的列表是:
_internal.classic_mode
agg.path.chunksize
animation.bitrate
animation.codec
animation.convert_args
animation.convert_path
animation.embed_limit
animation.ffmpeg_args
animation.ffmpeg_path
animation.frame_format
animation.html
animation.writer
axes.autolimit_mode
axes.axisbelow
axes.edgecolor
axes.facecolor
axes.formatter.limits
axes.formatter.min_exponent
axes.formatter.offset_threshold
axes.formatter.use_locale
axes.formatter.use_mathtext
axes.formatter.useoffset
axes.grid
axes.grid.axis
axes.grid.which
axes.labelcolor
axes.labelpad
axes.labelsize
axes.labelweight
axes.linewidth
axes.prop_cycle
axes.spines.bottom
axes.spines.left
axes.spines.right
axes.spines.top
axes.titlecolor
axes.titlelocation
axes.titlepad
axes.titlesize
axes.titleweight
axes.titley
axes.unicode_minus
axes.xmargin
axes.ymargin
axes.zmargin
axes3d.automargin
axes3d.grid
axes3d.xaxis.panecolor
axes3d.yaxis.panecolor
axes3d.zaxis.panecolor
后端
backend_fallback
boxplot.bootstrap
boxplot.boxprops.color
boxplot.boxprops.linestyle
boxplot.boxprops.linewidth
boxplot.capprops.color
boxplot.capprops.linestyle
boxplot.capprops.linewidth
boxplot.flierprops.color
boxplot.flierprops.linestyle
boxplot.flierprops.linewidth
boxplot.flierprops.marker
boxplot.flierprops.markeredgecolor
boxplot.flierprops.markeredgewidth
boxplot.flierprops.markerfacecolor
boxplot.flierprops.markersize
boxplot.meanline
boxplot.meanprops.color
boxplot.meanprops.linestyle
boxplot.meanprops.linewidth
boxplot.meanprops.marker
boxplot.meanprops.markeredgecolor
boxplot.meanprops.markerfacecolor
boxplot.meanprops.markersize
boxplot.medianprops.color
boxplot.medianprops.linestyle
boxplot.medianprops.linewidth
boxplot.notch
boxplot.patchartist
boxplot.showbox
boxplot.showcaps
boxplot.showfliers
boxplot.showmeans
boxplot.vertical
boxplot.whiskerprops.color
boxplot.whiskerprops.linestyle
boxplot.whiskerprops.linewidth
boxplot.whiskers
轮廓.算法
contour.corner_mask
contour.linewidth
contour.negative_linestyle
date.autoformatter.day
date.autoformatter.hour
date.autoformatter.微秒
date.autoformatter.minute
date.autoformatter.month
date.autoformatter.second
date.autoformatter.year
date.converter
日期.纪元
date.interval_multiples
docstring.hardcopy
errorbar.capsize
figure.autolayout
figure.constrained_layout.h_pad
figure.constrained_layout.hspace
figure.constrained_layout.use
figure.constrained_layout.w_pad
figure.constrained_layout.wspace
figure.dpi
figure.edgecolor
figure.facecolor
figure.figsize
figure.frameon
figure.hooks
figure.labelsize
figure.labelweight
figure.max_open_warning
figure.raise_window
figure.subplot.bottom
figure.subplot.hspace
figure.subplot.left
figure.subplot.right
figure.subplot.top
figure.subplot.wspace
figure.titlesize
figure.titleweight
font.cursive
font.family
font.fantasy
font.monospace
font.sans-serif
font.serif
font.size
font.stretch
font.style
font.variant
font.weight
grid.alpha
网格颜色
网格线样式
grid.linewidth
hatch.color
hatch.linewidth
hist.bins
image.aspect
image.cmap
image.composite_image
image.interpolation
image.interpolation_stage
图像.lut
image.origin
image.resample
交互式
keymap.back
keymap.copy
keymap.forward
keymap.fullscreen
keymap.grid
keymap.grid_minor
keymap.help
keymap.home
keymap.pan
keymap.quit
keymap.quit_all
keymap.save
keymap.xscale
keymap.yscale
keymap.zoom
legend.borderaxespad
legend.borderpad
legend.columnspacing
legend.edgecolor
legend.facecolor
legend.fancybox
legend.fontsize
legend.framealpha
legend.frameon
legend.handleheight
legend.handlelength
legend.handletextpad
legend.labelcolor
legend.labelspacing
legend.loc
legend.markerscale
legend.numpoints
legend.scatterpoints
legend.shadow
legend.title_fontsize
lines.antialiased
lines.color
lines.dash_capstyle
lines.dash_joinstyle
lines.dashdot_pattern
lines.dashed_pattern
lines.dotted_pattern
lines.linestyle
lines.linewidth
lines.marker
lines.markeredgecolor
lines.markeredgewidth
lines.markerfacecolor
lines.markersize
lines.scale_dashes
lines.solid_capstyle
lines.solid_joinstyle
macosx.window_mode
markers.fillstyle
mathtext.bf
mathtext.bfit
mathtext.cal
mathtext.default
mathtext.fallback
mathtext.fontset
mathtext.it
mathtext.rm
mathtext.sf
mathtext.tt
patch.antialiased
patch.edgecolor
patch.facecolor
patch.force_edgecolor
patch.linewidth
路径.效果
path.simplify
path.simplify_threshold
路径.草图
path.snap
pcolor.shading
pcolormesh.snap
pdf.compression
pdf.fonttype
pdf.inheritcolor
pdf.use14corefonts
pgf.preamble
pgf.rcfonts
pgf.texsystem
polaraxes.grid
ps.distiller.res
ps.fonttype
ps.papersize
ps.useafm
ps.usedistiller
savefig.bbox
savefig.directory
savefig.dpi
savefig.edgecolor
savefig.facecolor
savefig.format
savefig.orientation
savefig.pad_inches
savefig.transparent
scatter.edgecolors
scatter.marker
svg.fonttype
svg.hashsalt
svg.id
svg.image_inline
text.antialiased
text.color
text.hinting
text.hinting_factor
text.kerning_factor
text.latex.preamble
text.parse_math
text.usetex
时区
tk.window_focus
工具栏
webagg.地址
webagg.open_in_browser
webagg.port
webagg.port_retries
xaxis.labellocation
xtick.alignment
xtick.bottom
xtick.color
xtick.direction
xtick.labelbottom
xtick.labelcolor
xtick.labelsize
xtick.labeltop
xtick.major.bottom
xtick.major.pad
xtick.major.size
xtick.major.top
xtick.major.width
xtick.minor.bottom
xtick.minor.ndivs
xtick.minor.pad
xtick.minor.size
xtick.minor.top
xtick.minor.visible
xtick.minor.width
xtick.top
yaxis.labellocation
ytick.alignment
ytick.color
ytick.direction
ytick.labelcolor
ytick.labelleft
ytick.labelright
ytick.labelsize
ytick.left
ytick.major.left
ytick.major.pad
ytick.major.right
ytick.major.size
ytick.major.width
ytick.minor.left
ytick.minor.ndivs
ytick.minor.pad
ytick.minor.right
ytick.minor.size
ytick.minor.visible
ytick.minor.width
ytick.right
参见
- 使用matplotlibrc文件进行自定义
- find_all(pattern)[源代码][源代码]#
返回此 RcParams 字典的子集,其键与给定的
pattern
匹配,使用re.search()
。备注
对返回的字典的更改 不会 传播到父 RcParams 字典。
- matplotlib.rc_context(rc=None, fname=None)[源代码][源代码]#
返回一个上下文管理器,用于临时更改 rcParams。
上下文管理器不会重置
rcParams["后端"]
。通过上下文管理器调用和在上下文主体中更改的 rcParams 将在上下文退出时重置。
- 参数:
- rcdict
要临时设置的 rcParams。
- fnamestr 或 path-like
一个包含 Matplotlib rc 设置的文件。如果同时给出了 fname 和 rc ,则 rc 中的设置优先。
参见
- 使用matplotlibrc文件进行自定义
示例
通过字典传递显式值:
with mpl.rc_context({'interactive': False}): fig, ax = plt.subplots() ax.plot(range(3), range(3)) fig.savefig('example.png') plt.close(fig)
从文件加载设置:
with mpl.rc_context(fname='print.rc'): plt.plot(x, y) # uses 'print.rc'
在上下文主体中设置:
with mpl.rc_context(): # will be reset mpl.rcParams['lines.linewidth'] = 5 plt.plot(x, y)
- matplotlib.rc(group, **kwargs)[源代码][源代码]#
设置当前的
rcParams
。group 是 rc 的分组,例如,对于lines.linewidth
,分组是lines
,对于axes.facecolor
,分组是axes
,以此类推。分组也可以是一个组名的列表或元组,例如,(xtick, ytick)。kwargs 是一个字典属性名称/值对,例如,:rc('lines', linewidth=2, color='r')
设置当前的
rcParams
,相当于:rcParams['lines.linewidth'] = 2 rcParams['lines.color'] = 'r'
以下别名可供交互式用户使用,以节省输入时间:
别名
属性
'lw'
'linewidth'
'ls'
'linestyle'
'c'
'颜色'
'fc'
'facecolor'
'ec'
'edgecolor'
'喵'
'markeredgewidth'
'aa'
'抗锯齿'
因此,你可以将上述调用缩写为:
rc('lines', lw=2, c='r')
注意,你可以使用Python的kwargs字典功能来存储默认参数的字典。例如,你可以如下自定义字体rc:
font = {'family' : 'monospace', 'weight' : 'bold', 'size' : 'larger'} rc('font', **font) # pass in the font dict as kwargs
这使您可以轻松地在多个配置之间切换。使用
matplotlib.style.use('default')
或rcdefaults()
在更改后恢复默认的rcParams
。注释
通过使用普通的字典接口,也可以实现类似的功能,即
rcParams.update({"lines.linewidth": 2, ...})``(但 ``rcParams.update
不支持缩写或分组)。
- matplotlib.rcdefaults()[源代码][源代码]#
恢复 Matplotlib 内部默认样式的
rcParams
。样式黑名单中的
rcParams`(定义在 ``matplotlib.style.core.STYLE_BLACKLIST`
中)不会被更新。参见
matplotlib.rc_file_defaults
恢复 Matplotlib 最初加载的 rc 文件中的
rcParams
。matplotlib.style.use
使用特定的样式文件。调用
style.use('default')
以恢复默认样式。
- matplotlib.rc_file_defaults()[源代码][源代码]#
从 Matplotlib 加载的原始 rc 文件中恢复
rcParams
。样式黑名单中的
rcParams`(定义在 ``matplotlib.style.core.STYLE_BLACKLIST`
中)不会被更新。
- matplotlib.rc_file(fname, *, use_default_template=True)[源代码][源代码]#
从文件更新
rcParams
。样式黑名单中的
rcParams`(定义在 ``matplotlib.style.core.STYLE_BLACKLIST`
中)不会被更新。- 参数:
- fnamestr 或 path-like
一个包含 Matplotlib rc 设置的文件。
- use_default_template布尔
如果为 True,则在更新给定文件中的参数之前使用默认参数进行初始化。如果为 False,则当前配置保持不变,并且仅更新文件中指定的参数。
- matplotlib.rc_params_from_file(fname, fail_on_error=False, use_default_template=True)[源代码][源代码]#
从文件 fname 构建一个
RcParams
。- 参数:
- fnamestr 或 path-like
一个包含 Matplotlib rc 设置的文件。
- fail_on_error布尔
如果为真,当解析器无法转换参数时引发错误。
- use_default_template布尔
如果为 True,则在更新给定文件中的参数之前,使用默认参数进行初始化。如果为 False,配置类仅包含文件中指定的参数。(适用于更新字典。)
- matplotlib.get_configdir()[源代码][源代码]#
返回配置目录的字符串路径。
目录选择如下:
如果提供了 MPLCONFIGDIR 环境变量,则选择该变量。
在Linux上,遵循XDG规范,首先查看``$XDG_CONFIG_HOME``,如果已定义,或者``$HOME/.config``。在其他平台上,选择``$HOME/.matplotlib``。
如果所选目录存在且可写,则将其用作配置目录。
否则,创建一个临时目录,并将其用作配置目录。
- matplotlib.matplotlib_fname()[源代码][源代码]#
获取配置文件的位置。
文件位置按以下顺序确定
$PWD/matplotlibrc
$MATPLOTLIBRC
如果不是一个目录$MATPLOTLIBRC/matplotlibrc
$MPLCONFIGDIR/matplotlibrc
- 在Linux上,
$XDG_CONFIG_HOME/matplotlib/matplotlibrc
(如果$XDG_CONFIG_HOME
已定义)或者
$HOME/.config/matplotlib/matplotlibrc
(如果$XDG_CONFIG_HOME
未定义)
在其他平台上,如果定义了
$HOME
,则为$HOME/.matplotlib/matplotlibrc
最后,它会查找
$MATPLOTLIBDATA/matplotlibrc
,该文件应始终存在。
日志记录#
- matplotlib.set_loglevel(level)[源代码][源代码]#
配置 Matplotlib 的日志级别。
Matplotlib 使用标准库
logging
框架,根记录器为 'matplotlib'。这是一个辅助函数,用于:设置 Matplotlib 的根日志记录器级别
设置根日志处理程序的级别,如果处理程序尚不存在,则创建该处理程序。
通常,应调用
set_loglevel("info")
或set_loglevel("debug")
以获取额外的调试信息。安装自己的日志处理程序的用户或应用程序可能希望直接操作
logging.getLogger('matplotlib')
而不是使用此函数。- 参数:
- 级别
notset
,debug
,info
,warning
,error
,critical
处理程序的日志级别。
- 级别
注释
首次调用此函数时,会附加一个额外的处理程序到 Matplotlib 的根处理程序;此处理程序每次都会被重用,此函数仅操作记录器和处理程序的级别。
颜色映射和颜色序列#
- matplotlib.colormaps[源代码]#
包含Matplotlib已知名称的色图的容器。
通用注册表实例是
matplotlib.colormaps
。用户无需自行实例化ColormapRegistry
。读取访问使用类似字典的接口,将名称映射到
Colormap
s:import matplotlib as mpl cmap = mpl.colormaps['viridis']
返回的
Colormap
是副本,因此它们的修改不会改变颜色映射的全局定义。可以通过
ColormapRegistry.register
添加额外的色图:mpl.colormaps.register(my_colormap)
要获取所有已注册的颜色映射列表,您可以执行:
from matplotlib import colormaps list(colormaps)
- matplotlib.color_sequences[源代码]#
包含已知名称的颜色序列的容器。
通用注册表实例是
matplotlib.color_sequences
。用户不需要自己实例化ColorSequenceRegistry
。读取访问使用了一个类似字典的接口,将名称映射到颜色列表:
import matplotlib as mpl cmap = mpl.color_sequences['tab10']
返回的列表是副本,因此它们的修改不会改变颜色序列的全局定义。
可以通过
ColorSequenceRegistry.register
添加额外的颜色序列:mpl.color_sequences.register('rgb', ['r', 'g', 'b'])
杂项#
- matplotlib.get_cachedir()[源代码][源代码]#
返回缓存目录的字符串路径。
用于查找目录的过程与
get_configdir
相同,只是使用了$XDG_CACHE_HOME
/$HOME/.cache
替代。