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
,它们可以极大地简化脚本编写。有关隐式和显式接口之间权衡的解释,请参阅 Matplotlib 应用程序接口 (API)。
模块包括
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
文件覆盖。使用
设置 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 docstrings) 会引用 MATLAB®,它是 The MathWorks, Inc. 的注册商标。
后端管理#
- matplotlib.use(backend, *, force=True)[source]#
选择用于渲染和 GUI 集成的后端。
如果 pyplot 已经导入,则使用
switch_backend
,如果新后端与当前后端不同,所有 Figure 都将被关闭。- 参数:
- backendstr
要切换到的后端。这可以是标准后端名称之一(不区分大小写)
交互式后端: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),则无法切换到交互式后端。切换到非交互式后端始终可能。
- forcebool, default: True
如果为 True(默认值),则在后端无法设置时(无论是导入失败还是不兼容的 GUI 交互式框架已在运行)引发
ImportError
;如果为 False,则静默忽略失败。
- matplotlib.get_backend(*, auto_select=True)[source]#
返回当前后端的名称。
- 参数:
- auto_selectbool, default: True
如果尚未选择后端,是否触发后端解析。如果为 True,则确保返回有效后端。如果为 False,则在尚未选择后端时返回 None。
自 3.10 版本新增。
临时性
auto_select 标志是临时性的。它可能会在不事先通知的情况下更改或删除。
另请参阅
- matplotlib.interactive(b)[source]#
设置是否在每个绘图命令(例如
pyplot.xlabel
)后重新绘制。
- matplotlib.is_interactive()[source]#
返回是否在每个绘图命令后重新绘制。
注意
此函数仅供后端使用。终端用户应改用
pyplot.isinteractive
。
默认值和样式#
- class matplotlib.RcParams(*args, **kwargs)[source]#
一个类似字典的键值存储,用于配置参数,包括验证。
验证函数在
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.mouserotationstyle
axes3d.trackballborder
axes3d.trackballsize
axes3d.xaxis.panecolor
axes3d.yaxis.panecolor
axes3d.zaxis.panecolor
backend
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.algorithm
contour.corner_mask
contour.linewidth
contour.negative_linestyle
date.autoformatter.day
date.autoformatter.hour
date.autoformatter.microsecond
date.autoformatter.minute
date.autoformatter.month
date.autoformatter.second
date.autoformatter.year
date.converter
date.epoch
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.color
grid.linestyle
grid.linewidth
hatch.color
hatch.linewidth
hist.bins
image.aspect
image.cmap
image.composite_image
image.interpolation
image.interpolation_stage
image.lut
image.origin
image.resample
interactive
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.effects
path.simplify
path.simplify_threshold
path.sketch
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
timezone
tk.window_focus
toolbar
webagg.address
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
另请参阅
- find_all(pattern)[source]#
返回此 RcParams 字典的子集,其键使用
re.search()
匹配给定的pattern
。注意
返回的字典的更改不会传播到父 RcParams 字典。
- matplotlib.rc_context(rc=None, fname=None)[source]#
返回一个用于临时更改 rcParams 的上下文管理器。
rcParams["backend"]
不会被上下文管理器重置。通过上下文管理器调用和在上下文体中更改的 rcParams 将在上下文退出时重置。
- 参数:
- rcdict
要临时设置的 rcParams。
- fnamestr 或 path-like
一个包含 Matplotlib rc 设置的文件。如果同时给出 fname 和 rc,则 rc 中的设置优先。
另请参阅
示例
通过字典传递显式值
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)[source]#
设置当前的
rcParams
。group 是 rc 的分组,例如,对于lines.linewidth
,分组是lines
;对于axes.facecolor
,分组是axes
,依此类推。group 也可以是组名列表或元组,例如 (xtick, ytick)。kwargs 是一个字典属性名/值对,例如:rc('lines', linewidth=2, color='r')
设置当前的
rcParams
,等同于rcParams['lines.linewidth'] = 2 rcParams['lines.color'] = 'r'
以下别名可用于交互式用户节省输入:
别名
属性
'lw'
'linewidth'
'ls'
'linestyle'
'c'
'color'
'fc'
'facecolor'
'ec'
'edgecolor'
'mew'
'markeredgewidth'
'aa'
'antialiased'
因此,上述调用可以缩写为:
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()[source]#
从 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()[source]#
从 Matplotlib 加载的原始 rc 文件恢复
rcParams
。样式黑名单中的
rcParams
(定义在matplotlib.style.core.STYLE_BLACKLIST
中)不会被更新。
- matplotlib.rc_file(fname, *, use_default_template=True)[source]#
从文件更新
rcParams
。样式黑名单中的
rcParams
(定义在matplotlib.style.core.STYLE_BLACKLIST
中)不会被更新。- 参数:
- fnamestr 或 path-like
一个包含 Matplotlib rc 设置的文件。
- use_default_templatebool
如果为 True,则在用给定文件中的参数更新之前,先使用默认参数进行初始化。如果为 False,则当前配置保持不变,仅更新文件中指定的参数。
- matplotlib.rc_params_from_file(fname, fail_on_error=False, use_default_template=True)[source]#
从文件 fname 构造一个
RcParams
。- 参数:
- fnamestr 或 path-like
一个包含 Matplotlib rc 设置的文件。
- fail_on_errorbool
如果为 True,则当解析器未能转换参数时引发错误。
- use_default_templatebool
如果为 True,则在用给定文件中的参数更新之前,先用默认参数进行初始化。如果为 False,则配置类仅包含文件中指定的参数。(对于更新字典很有用。)
- matplotlib.get_configdir()[source]#
返回配置目录的字符串路径。
目录选择如下:
如果提供了 MPLCONFIGDIR 环境变量,则选择该目录。
在 Linux 上,遵循 XDG 规范,首先查找
$XDG_CONFIG_HOME
(如果已定义),或$HOME/.config
。在其他平台上,选择$HOME/.matplotlib
。如果选定的目录存在且可写,则将其用作配置目录。
否则,创建一个临时目录,并将其用作配置目录。
- matplotlib.matplotlib_fname()[source]#
获取配置文件位置。
文件位置按以下顺序确定:
$PWD/matplotlibrc
$MATPLOTLIBRC
如果它不是目录$MATPLOTLIBRC/matplotlibrc
$MPLCONFIGDIR/matplotlibrc
- 在 Linux 上:
$XDG_CONFIG_HOME/matplotlib/matplotlibrc
(如果定义了$XDG_CONFIG_HOME
)或
$HOME/.config/matplotlib/matplotlibrc
(如果未定义$XDG_CONFIG_HOME
)
在其他平台上: -
$HOME/.matplotlib/matplotlibrc
(如果定义了$HOME
)最后,它会在
$MATPLOTLIBDATA/matplotlibrc
中查找,该文件应该始终存在。
日志#
- matplotlib.set_loglevel(level)[source]#
配置 Matplotlib 的日志级别。
Matplotlib 使用标准库
logging
框架,在根记录器 'matplotlib' 下。这是一个辅助函数,用于:设置 Matplotlib 的根记录器级别
设置根记录器处理程序的级别,如果处理程序尚不存在则创建它
通常,应该调用
set_loglevel("info")
或set_loglevel("debug")
以获取额外的调试信息。安装自己日志处理程序的用户或应用程序可能希望直接操作
logging.getLogger('matplotlib')
而不是使用此函数。- 参数:
- level{"notset", "debug", "info", "warning", "error", "critical"}
处理程序的日志级别。
备注
首次调用此函数时,会将一个额外的处理程序附加到 Matplotlib 的根处理程序;此处理程序每次都会被重用,此函数仅操作记录器和处理程序的级别。
色彩映射和颜色序列#
- matplotlib.colormaps[source]#
已知 Matplotlib 命名的色彩映射容器。
通用注册表实例是
matplotlib.colormaps
。用户无需自行实例化ColormapRegistry
。读访问使用类似字典的接口,将名称映射到
Colormap
s。import matplotlib as mpl cmap = mpl.colormaps['viridis']
返回的
Colormap
s 是副本,因此它们的修改不会改变色彩映射的全局定义。可以通过
ColormapRegistry.register
添加额外的色彩映射。mpl.colormaps.register(my_colormap)
要获取所有注册色彩映射的列表,您可以执行以下操作:
from matplotlib import colormaps list(colormaps)
- matplotlib.color_sequences[source]#
已知 Matplotlib 命名的颜色序列容器。
通用注册表实例是
matplotlib.color_sequences
。用户无需自行实例化ColorSequenceRegistry
。读访问使用类似字典的接口,将名称映射到颜色列表。
import matplotlib as mpl colors = mpl.color_sequences['tab10']
有关内置颜色序列的列表,请参阅 命名颜色序列。返回的列表是副本,因此它们的修改不会改变颜色序列的全局定义。
可以通过
ColorSequenceRegistry.register
添加额外的颜色序列。mpl.color_sequences.register('rgb', ['r', 'g', 'b'])
杂项#
- matplotlib.get_cachedir()[source]#
返回缓存目录的字符串路径。
查找目录的过程与
get_configdir
相同,但使用$XDG_CACHE_HOME
/$HOME/.cache
代替。