Note
Go to the end to download the full example code.
Quick start guide# 快速入门指南 #
This tutorial covers some basic usage patterns and best practices to
help you get started with Matplotlib.
本教程涵盖了一些基本使用模式和最佳实践,帮助你开始使用 Matplotlib。
import matplotlib.pyplot as plt
import numpy as np
A simple example# 一个简单的示例 #
Matplotlib graphs your data on Figure
s (e.g., windows, Jupyter
widgets, etc.), each of which can contain one or more Axes
, an
area where points can be specified in terms of x-y coordinates (or theta-r
in a polar plot, x-y-z in a 3D plot, etc.). The simplest way of
creating a Figure with an Axes is using pyplot.subplots
. We can then use
Axes.plot
to draw some data on the Axes, and show
to display
the figure:
Matplotlib 在 Figure
上绘制你的数据(例如,窗口、Jupyter 小部件等),每个 Figure
可以包含一个或多个 Axes
,这是一个可以用 x-y 坐标(或在极坐标图中用 theta-r,在 3D 图中用 x-y-z 等)指定点的区域。创建一个带有 Axes 的 Figure 最简单的方法是使用 pyplot.subplots
。然后我们可以使用 Axes.plot
在 Axes 上绘制一些数据,并使用 show
显示该图形:
fig, ax = plt.subplots() # Create a figure containing a single Axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the Axes.
plt.show() # Show the figure.

Depending on the environment you are working in, plt.show()
can be left
out. This is for example the case with Jupyter notebooks, which
automatically show all figures created in a code cell.
根据你工作的环境,可以省略 plt.show()
。例如,在 Jupyter 笔记本中,代码单元中创建的所有图形都会自动显示。
Parts of a Figure#
图形的组成部分 #
Here are the components of a Matplotlib Figure.
以下是 Matplotlib 图形的组成部分。

Figure
#
The whole figure. The Figure keeps
track of all the child Axes
, a group of
'special' Artists (titles, figure legends, colorbars, etc.), and
even nested subfigures.
整个图形。Figure 会跟踪所有子元素 Axes
,一组"特殊"的 Artist(标题、图形图例、色条等),甚至嵌套的子图形。
Typically, you'll create a new Figure through one of the following
functions:
通常,您会通过以下函数之一创建一个新的 Figure:
fig = plt.figure() # an empty figure with no Axes
fig, ax = plt.subplots() # a figure with a single Axes
fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
# a figure with one Axes on the left, and two on the right:
fig, axs = plt.subplot_mosaic([['left', 'right_top'],
['left', 'right_bottom']])
subplots()
and subplot_mosaic
are convenience functions
that additionally create Axes objects inside the Figure, but you can also
manually add Axes later on.
subplots()
和 subplot_mosaic
是便捷函数,它们会在 Figure 内部额外创建 Axes 对象,但你也可以稍后手动添加 Axes。
For more on Figures, including panning and zooming, see Introduction to Figures.
有关更多关于图形的内容,包括平移和缩放,请参阅图形简介。
Axes
#
An Axes is an Artist attached to a Figure that contains a region for
plotting data, and usually includes two (or three in the case of 3D)
Axis
objects (be aware of the difference
between Axes and Axis) that provide ticks and tick labels to
provide scales for the data in the Axes. Each Axes
also
has a title
(set via set_title()
), an x-label (set via
set_xlabel()
), and a y-label set via
set_ylabel()
).
一个 Axes 是一个附加到 Figure 上的 Artist,它包含一个用于绘制数据的区域,并且通常包括两个(在 3D 情况下为三个) Axis
对象(注意 Axes 和 Axis 之间的区别),这些对象提供刻度和刻度标签,为 Axes 中的数据提供标度。每个 Axes
还有一个标题(通过 set_title()
设置)、一个 x 轴标签(通过 set_xlabel()
设置)和一个 y 轴标签(通过 set_ylabel()
设置)。
The Axes
methods are the primary interface for configuring
most parts of your plot (adding data, controlling axis scales and
limits, adding labels etc.).
Axes
方法是配置你图形大部分部分的主要接口(添加数据、控制坐标轴尺度和范围、添加标签等)。
Axis
#
These objects set the scale and limits and generate ticks (the marks
on the Axis) and ticklabels (strings labeling the ticks). The location
of the ticks is determined by a Locator
object and the
ticklabel strings are formatted by a Formatter
. The
combination of the correct Locator
and Formatter
gives very fine
control over the tick locations and labels.
这些对象设定了刻度范围并生成刻度线(轴上的标记)和刻度标签(用于标记刻度的字符串)。刻度线的位置由一个 Locator
对象决定,而刻度标签字符串则由一个 Formatter
格式化。正确组合 Locator
和 Formatter
可以非常精细地控制刻度线和标签的位置。
Artist
#
Basically, everything visible on the Figure is an Artist (even
Figure
, Axes
, and Axis
objects). This includes
Text
objects, Line2D
objects, collections
objects, Patch
objects, etc. When the Figure is rendered, all of the
Artists are drawn to the canvas. Most Artists are tied to an Axes; such
an Artist cannot be shared by multiple Axes, or moved from one to another.
基本上,Figure 上所有可见的内容都是一个 Artist(包括 Figure
、 Axes
和 Axis
对象)。这包括 Text
对象、 Line2D
对象、 collections
对象、 Patch
对象等。当 Figure 渲染时,所有 Artist 都会被绘制到画布上。大多数 Artist 都与一个 Axes 相关联;这样的 Artist 不能被多个 Axes 共享,或从一个 Axes 移动到另一个 Axes。
Types of inputs to plotting functions#
绘图函数的输入类型 #
Plotting functions expect numpy.array
or numpy.ma.masked_array
as
input, or objects that can be passed to numpy.asarray
.
Classes that are similar to arrays ('array-like') such as pandas
data objects and numpy.matrix
may not work as intended. Common convention
is to convert these to numpy.array
objects prior to plotting.
For example, to convert a numpy.matrix
绘图函数期望输入 numpy.array
或 numpy.ma.masked_array
,或可传递给 numpy.asarray
的对象。类似于数组的类('array-like')如 pandas
数据对象和 numpy.matrix
可能无法按预期工作。常见的惯例是在绘图前将这些转换为 numpy.array
对象。例如,要将一个 numpy.matrix
转换为
b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b)
Most methods will also parse a string-indexable object like a dict, a
structured numpy array, or a pandas.DataFrame
. Matplotlib allows you
to provide the data
keyword argument and generate plots passing the
strings corresponding to the x and y variables.
大多数方法也会解析字符串索引对象,如字典、结构化 numpy 数组或 pandas.DataFrame
。Matplotlib 允许你提供 data
关键字参数,并通过传递对应于 x 和 y 变量的字符串来生成图表。
np.random.seed(19680801) # seed the random number generator.
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b')

Coding styles# 编程风格 #
The explicit and the implicit interfaces#
显式接口和隐式接口 #
As noted above, there are essentially two ways to use Matplotlib:
如上所述,使用 Matplotlib 基本有两种方式:
Explicitly create Figures and Axes, and call methods on them (the "object-oriented (OO) style").
显式创建 Figures 和 Axes,并在它们上调用方法(面向对象(OO)风格)。Rely on pyplot to implicitly create and manage the Figures and Axes, and use pyplot functions for plotting.
依赖 pyplot 隐式创建和管理 Figure 和 Axes,并使用 pyplot 函数进行绘图。
See Matplotlib Application Interfaces (APIs) for an explanation of the tradeoffs between the
implicit and explicit interfaces.
参见 Matplotlib 应用接口(API)了解隐式接口和显式接口之间的权衡。
So one can use the OO-style
因此可以使用面向对象风格
x = np.linspace(0, 2, 100) # Sample data.
# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear') # Plot some data on the Axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the Axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the Axes.
ax.set_ylabel('y label') # Add a y-label to the Axes.
ax.set_title("Simple Plot") # Add a title to the Axes.
ax.legend() # Add a legend.

or the pyplot-style: 或者使用 pyplot 风格:
x = np.linspace(0, 2, 100) # Sample data.
plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear') # Plot some data on the (implicit) Axes.
plt.plot(x, x**2, label='quadratic') # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()

(In addition, there is a third approach, for the case when embedding
Matplotlib in a GUI application, which completely drops pyplot, even for
figure creation. See the corresponding section in the gallery for more info:
Embedding Matplotlib in graphical user interfaces.)
此外,还有一种方法,适用于将 Matplotlib 嵌入 GUI 应用程序的情况,这种方法完全放弃了 pyplot,甚至对于图形创建也是如此。有关更多信息,请参阅画廊中相应的部分:将 Matplotlib 嵌入图形用户界面。
Matplotlib's documentation and examples use both the OO and the pyplot
styles. In general, we suggest using the OO style, particularly for
complicated plots, and functions and scripts that are intended to be reused
as part of a larger project.
Matplotlib 的文档和示例都使用了面向对象(OO)和 pyplot 两种风格。通常,我们建议使用面向对象风格,特别是对于复杂的图表、以及打算作为更大项目一部分进行重用的函数和脚本。
However, the pyplot style can be very convenient
for quick interactive work.
然而,pyplot 风格对于快速交互式工作非常方便。
Note 注意
You may find older examples that use the pylab
interface,
via from pylab import *
. This approach is strongly deprecated.
你可能会找到使用 pylab
接口的一些旧示例,通过 from pylab import *
。这种方法强烈不推荐。
Making a helper functions#
创建辅助函数 #
If you need to make the same plots over and over again with different data
sets, or want to easily wrap Matplotlib methods, use the recommended
signature function below.
如果你需要用不同的数据集反复绘制相同的图表,或者想要轻松地封装 Matplotlib 方法,请使用下面推荐的签名函数。
which you would then use twice to populate two subplots:
你可以使用它两次来填充两个子图:

Note that if you want to install these as a python package, or any other
customizations you could use one of the many templates on the web;
Matplotlib has one at mpl-cookiecutter
请注意,如果你想要将这些安装为 Python 包,或进行任何其他自定义,你可以使用网络上的许多模板之一;Matplotlib 有一个名为 mpl-cookiecutter 的模板
Styling Artists# 美化艺术家样式 #
Most plotting methods have styling options for the Artists, accessible either
when a plotting method is called, or from a "setter" on the Artist. In the
plot below we manually set the color, linewidth, and linestyle of the
Artists created by plot
, and we set the linestyle of the second line
after the fact with set_linestyle
.
大多数绘图方法都有针对艺术品的样式选项,这些选项可以在调用绘图方法时访问,也可以通过艺术品的"setter"访问。在下面的图中,我们手动设置了由 plot
创建的艺术品的颜色、线宽和线型,并且使用 set_linestyle
事后设置了第二条线的线型。

Colors# 颜色 #
Matplotlib has a very flexible array of colors that are accepted for most
Artists; see allowable color definitions for a
list of specifications. Some Artists will take multiple colors. i.e. for
a scatter
plot, the edge of the markers can be different colors
from the interior:
Matplotlib 支持非常灵活的颜色数组,大多数 Artist 都可以接受这些颜色;请参阅允许的颜色定义以获取规范列表。某些 Artist 可以接受多种颜色。例如,对于 scatter
图,标记的边缘颜色可以与内部颜色不同:
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k')

Linewidths, linestyles, and markersizes#
线宽、线型和标记大小 #
Line widths are typically in typographic points (1 pt = 1/72 inch) and
available for Artists that have stroked lines. Similarly, stroked lines
can have a linestyle. See the linestyles example.
线宽通常以印刷点为单位(1 pt = 1/72 英寸),适用于具有描边线条的艺术家。类似地,描边线条可以具有线型。请参阅线型示例。
Marker size depends on the method being used. plot
specifies
markersize in points, and is generally the "diameter" or width of the
marker. scatter
specifies markersize as approximately
proportional to the visual area of the marker. There is an array of
markerstyles available as string codes (see markers
), or
users can define their own MarkerStyle
(see
Marker reference):
标记大小取决于所使用的方法。 plot
指定标记大小以点为单位,通常表示标记的“直径”或宽度。 scatter
指定标记大小大致与标记的视觉面积成比例。有字符串代码形式的标记样式数组可用(参见 markers
),或者用户可以自定义 MarkerStyle
(参见标记参考):

Labelling plots# 标注图表 #
Axes labels and text#
坐标轴标签和文本 #
set_xlabel
, set_ylabel
, and set_title
are used to
add text in the indicated locations (see Text in Matplotlib
for more discussion). Text can also be directly added to plots using
text
:
set_xlabel
、 set_ylabel
和 set_title
用于在指定位置添加文本(有关更多讨论,请参阅 Matplotlib 中的文本)。也可以使用 text
直接将文本添加到图表中:
mu, sigma = 115, 15
x = mu + sigma * np.random.randn(10000)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
# the histogram of the data
n, bins, patches = ax.hist(x, 50, density=True, facecolor='C0', alpha=0.75)
ax.set_xlabel('Length [cm]')
ax.set_ylabel('Probability')
ax.set_title('Aardvark lengths\n (not really)')
ax.text(75, .025, r'$\mu=115,\ \sigma=15$')
ax.axis([55, 175, 0, 0.03])
ax.grid(True)

All of the text
functions return a matplotlib.text.Text
instance. Just as with lines above, you can customize the properties by
passing keyword arguments into the text functions:
所有 text
函数都返回一个 matplotlib.text.Text
实例。就像上面提到的线条一样,你可以通过向文本函数传递关键字参数来自定义属性:
t = ax.set_xlabel('my data', fontsize=14, color='red')
These properties are covered in more detail in
Text properties and layout.
这些属性在文本属性和布局中有更详细的说明。
Using mathematical expressions in text#
在文本中使用数学表达式
Matplotlib accepts TeX equation expressions in any text expression.
For example to write the expression
Matplotlib 接受 TeX 方程表达式在任意文本表达式中。例如要在标题中写入表达式
ax.set_title(r'$\sigma_i=15$')
where the r
preceding the title string signifies that the string is a
raw string and not to treat backslashes as python escapes.
Matplotlib has a built-in TeX expression parser and
layout engine, and ships its own math fonts – for details see
Writing mathematical expressions. You can also use LaTeX directly to format
your text and incorporate the output directly into your display figures or
saved postscript – see Text rendering with LaTeX.
在标题字符串前的 r
表示该字符串是一个原始字符串,不应将反斜杠视为 Python 转义字符。Matplotlib 拥有内置的 TeX 表达式解析器和布局引擎,并提供自己的数学字体——详细信息请参阅《编写数学表达式》。您也可以直接使用 LaTeX 来格式化文本,并将输出直接嵌入到显示的图形或保存的 postscript 文件中——请参阅《使用 LaTeX 渲染文本》。
Annotations# 注释 #
We can also annotate points on a plot, often by connecting an arrow pointing
to xy, to a piece of text at xytext:
我们也可以在图表上标注点,通常是通过一个指向 xy 的箭头连接到 xytext 处的文本:
fig, ax = plt.subplots(figsize=(5, 2.7))
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = ax.plot(t, s, lw=2)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.set_ylim(-2, 2)

In this basic example, both xy and xytext are in data coordinates.
There are a variety of other coordinate systems one can choose -- see
Basic annotation and Advanced annotation for
details. More examples also can be found in
Annotate plots.
在这个基本示例中,xy 和 xytext 都位于数据坐标中。可以选择多种其他坐标系——请参阅基本注释和高级注释以获取详细信息。更多示例也可以在注释图表中找到。
Legends# 图例 #
Often we want to identify lines or markers with a Axes.legend
:
通常我们想要用 Axes.legend
来标识线条或标记:

Legends in Matplotlib are quite flexible in layout, placement, and what
Artists they can represent. They are discussed in detail in
Legend guide.
Matplotlib 中的图例在布局、位置以及能表示的 Artist 方面非常灵活。它们在图例指南中有详细讨论。
Axis scales and ticks#
坐标轴刻度和刻度 #
Each Axes has two (or three) Axis
objects representing the x- and
y-axis. These control the scale of the Axis, the tick locators and the
tick formatters. Additional Axes can be attached to display further Axis
objects.
每个 Axes 对象有两个(或三个) Axis
对象,分别代表 x 轴和 y 轴。这些对象控制轴的刻度、刻度定位器和刻度格式。可以附加额外的 Axes 对象来显示更多的轴刻度对象。
Scales# 刻度
In addition to the linear scale, Matplotlib supplies non-linear scales,
such as a log-scale. Since log-scales are used so much there are also
direct methods like loglog
, semilogx
, and
semilogy
. There are a number of scales (see
Scales overview for other examples). Here we set the scale
manually:
除了线性刻度,Matplotlib 还提供了非线性刻度,例如对数刻度。由于对数刻度使用非常频繁,因此也有直接的方法,如 loglog
、 semilogx
和 semilogy
。有多种刻度可供选择(参见刻度概述以了解其他示例)。在这里我们手动设置刻度:

The scale sets the mapping from data values to spacing along the Axis. This
happens in both directions, and gets combined into a transform, which
is the way that Matplotlib maps from data coordinates to Axes, Figure, or
screen coordinates. See Transformations Tutorial.
比例尺设定了数据值到轴上间距的映射关系。这发生在两个方向上,并组合成一个变换,这是 Matplotlib 从数据坐标映射到轴、图形或屏幕坐标的方式。参见变换教程。
Tick locators and formatters#
刻度定位器和格式化器 #
Each Axis has a tick locator and formatter that choose where along the
Axis objects to put tick marks. A simple interface to this is
set_xticks
:
每个轴都有一个刻度定位器和格式器,用于选择在轴对象上的何处放置刻度标记。这个功能的简单接口是 set_xticks
:
fig, axs = plt.subplots(2, 1, layout='constrained')
axs[0].plot(xdata, data1)
axs[0].set_title('Automatic ticks')
axs[1].plot(xdata, data1)
axs[1].set_xticks(np.arange(0, 100, 30), ['zero', '30', 'sixty', '90'])
axs[1].set_yticks([-1.5, 0, 1.5]) # note that we don't need to specify labels
axs[1].set_title('Manual ticks')

Different scales can have different locators and formatters; for instance
the log-scale above uses LogLocator
and LogFormatter
. See
Tick locators and
Tick formatters for other formatters and
locators and information for writing your own.
不同的标度可以使用不同的定位器和格式器;例如,上面的对数标度使用 LogLocator
和 LogFormatter
。有关其他格式器和定位器以及编写自己的定位器和格式器的信息,请参阅定位器和刻度格式器。
Plotting dates and strings#
绘制日期和字符串 #
Matplotlib can handle plotting arrays of dates and arrays of strings, as
well as floating point numbers. These get special locators and formatters
as appropriate. For dates:
Matplotlib 可以处理日期数组和字符串数组,以及浮点数。这些数据会根据需要获得特殊的定位器和格式化器。对于日期:
from matplotlib.dates import ConciseDateFormatter
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
dates = np.arange(np.datetime64('2021-11-15'), np.datetime64('2021-12-25'),
np.timedelta64(1, 'h'))
data = np.cumsum(np.random.randn(len(dates)))
ax.plot(dates, data)
ax.xaxis.set_major_formatter(ConciseDateFormatter(ax.xaxis.get_major_locator()))

For more information see the date examples
(e.g. Date tick labels)
有关更多信息,请参阅日期示例(例如日期刻度标签)
For strings, we get categorical plotting (see:
Plotting categorical variables).
对于字符串,我们得到分类绘图(参见:绘制分类变量)。
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
categories = ['turnips', 'rutabaga', 'cucumber', 'pumpkins']
ax.bar(categories, np.random.rand(len(categories)))

One caveat about categorical plotting is that some methods of parsing
text files return a list of strings, even if the strings all represent
numbers or dates. If you pass 1000 strings, Matplotlib will think you
meant 1000 categories and will add 1000 ticks to your plot!
关于分类绘图有一个注意事项:某些解析文本文件的方法即使字符串全部表示数字或日期,也会返回字符串列表。如果你传入 1000 个字符串,Matplotlib 会认为你表示有 1000 个类别,并在你的图中添加 1000 个刻度!
Additional Axis objects#
额外的轴对象 #
Plotting data of different magnitude in one chart may require
an additional y-axis. Such an Axis can be created by using
twinx
to add a new Axes with an invisible x-axis and a y-axis
positioned at the right (analogously for twiny
). See
Plots with different scales for another example.
在一个图表中绘制不同量级的数据可能需要额外的 y 轴。这样的轴可以通过使用 twinx
来创建一个新的 Axes,它具有一个不可见的 x 轴和一个位于右侧的 y 轴(类似地,对于 twiny
)。另见不同量级的图表示例。
Similarly, you can add a secondary_xaxis
or
secondary_yaxis
having a different scale than the main Axis to
represent the data in different scales or units. See
Secondary Axis for further
examples.
类似地,你可以添加一个 secondary_xaxis
或 secondary_yaxis
,使其具有与主轴不同的量级,以用不同的量级或单位表示数据。另见次要轴的更多示例。
fig, (ax1, ax3) = plt.subplots(1, 2, figsize=(7, 2.7), layout='constrained')
l1, = ax1.plot(t, s)
ax2 = ax1.twinx()
l2, = ax2.plot(t, range(len(t)), 'C1')
ax2.legend([l1, l2], ['Sine (left)', 'Straight (right)'])
ax3.plot(t, s)
ax3.set_xlabel('Angle [rad]')
ax4 = ax3.secondary_xaxis('top', (np.rad2deg, np.deg2rad))
ax4.set_xlabel('Angle [°]')

Color mapped data# 颜色映射数据 #
Often we want to have a third dimension in a plot represented by colors in
a colormap. Matplotlib has a number of plot types that do this:
通常我们希望在图中用颜色映射来表示第三维度。Matplotlib 有多种绘图类型可以实现这一点:
from matplotlib.colors import LogNorm
X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128))
Z = (1 - X/2 + X**5 + Y**3) * np.exp(-X**2 - Y**2)
fig, axs = plt.subplots(2, 2, layout='constrained')
pc = axs[0, 0].pcolormesh(X, Y, Z, vmin=-1, vmax=1, cmap='RdBu_r')
fig.colorbar(pc, ax=axs[0, 0])
axs[0, 0].set_title('pcolormesh()')
co = axs[0, 1].contourf(X, Y, Z, levels=np.linspace(-1.25, 1.25, 11))
fig.colorbar(co, ax=axs[0, 1])
axs[0, 1].set_title('contourf()')
pc = axs[1, 0].imshow(Z**2 * 100, cmap='plasma', norm=LogNorm(vmin=0.01, vmax=100))
fig.colorbar(pc, ax=axs[1, 0], extend='both')
axs[1, 0].set_title('imshow() with LogNorm()')
pc = axs[1, 1].scatter(data1, data2, c=data3, cmap='RdBu_r')
fig.colorbar(pc, ax=axs[1, 1], extend='both')
axs[1, 1].set_title('scatter()')

Colormaps# 色彩映射
These are all examples of Artists that derive from ScalarMappable
objects. They all can set a linear mapping between vmin and vmax into
the colormap specified by cmap. Matplotlib has many colormaps to choose
from (Choosing Colormaps in Matplotlib) you can make your
own (Creating Colormaps in Matplotlib) or download as
third-party packages.
这些都是继承自 ScalarMappable
对象的 Artist 示例。它们都可以在 vmin 和 vmax 之间设置线性映射到由 cmap 指定的 colormap。Matplotlib 提供了许多可供选择的 colormap(Matplotlib 中的 colormap 选择),你可以自己创建(Matplotlib 中的 colormap 创建),或者作为第三方包下载。
Normalizations# 归一化方法 #
Sometimes we want a non-linear mapping of the data to the colormap, as
in the LogNorm
example above. We do this by supplying the
ScalarMappable with the norm argument instead of vmin and vmax.
More normalizations are shown at Colormap normalization.
有时我们希望数据到 colormap 的映射是非线性的,就像上面 LogNorm
示例中的情况。我们通过向 ScalarMappable 提供 norm 参数而不是 vmin 和 vmax 来实现这一点。更多归一化方法请参考 Colormap 归一化。
Colorbars# 色条 #
Adding a colorbar
gives a key to relate the color back to the
underlying data. Colorbars are figure-level Artists, and are attached to
a ScalarMappable (where they get their information about the norm and
colormap) and usually steal space from a parent Axes.
添加一个 colorbar
可以提供一个与底层数据关联的键。Colorbars 是图级别的 Artist,它们连接到 ScalarMappable(从中获取关于规范和调色板的信息),并且通常从父 Axes 借用空间。
Placement of
colorbars can be complex: see
Placing colorbars for
details. You can also change the appearance of colorbars with the
extend keyword to add arrows to the ends, and shrink and aspect to
control the size. Finally, the colorbar will have default locators
and formatters appropriate to the norm. These can be changed as for
other Axis objects.
Colorbars 的位置可能很复杂:请参阅“放置 colorbars”以获取详细信息。您还可以使用 extend 关键字更改 colorbars 的外观,在两端添加箭头,并使用 shrink 和 aspect 控制大小。最后,colorbar 将具有适合规范默认的定位器和格式化器。这些可以像其他 Axis 对象一样更改。
Working with multiple Figures and Axes#
处理多个 Figures 和 Axes #
You can open multiple Figures with multiple calls to
fig = plt.figure()
or fig2, ax = plt.subplots()
. By keeping the
object references you can add Artists to either Figure.
你可以通过多次调用 fig = plt.figure()
或 fig2, ax = plt.subplots()
来打开多个 Figure。通过保留对象引用,你可以将 Artist 添加到任意一个 Figure 中。
Multiple Axes can be added a number of ways, but the most basic is
plt.subplots()
as used above. One can achieve more complex layouts,
with Axes objects spanning columns or rows, using subplot_mosaic
.
可以通过多种方式添加多个坐标轴,但最基本的是上面使用的方法 plt.subplots()
。要实现更复杂的布局,例如跨越列或行的坐标轴对象,可以使用方法 subplot_mosaic
。

Matplotlib has quite sophisticated tools for arranging Axes: See
Arranging multiple Axes in a Figure and Complex and semantic figure composition (subplot_mosaic).
Matplotlib 拥有非常复杂的工具来排列 Axes:参见在图中排列多个 Axes 以及复杂和语义化的图组成(subplot_mosaic)。
More reading# 更多阅读 #
For more plot types see Plot types and the
API reference, in particular the
Axes API.
更多图表类型请参阅“图表类型”和“API 参考”,特别是“轴 API”。
Total running time of the script: (0 minutes 7.674 seconds)
脚本的总运行时间:(0 分钟 7.674 秒)