注意
到末尾下载完整示例代码。
绘图的生命周期#
本教程旨在展示使用 Matplotlib 进行单次可视化的开始、中间和结束。我们将从原始数据开始,最终保存定制化可视化图表。在此过程中,我们会尝试强调 Matplotlib 的一些实用功能和最佳实践。
注意
本教程基于 Chris Moffitt 这篇优秀的博客文章。由 Chris Holdgraf 将其改编成本教程。
关于显式与隐式接口的说明#
Matplotlib 提供了两种接口。有关显式和隐式接口之间权衡的解释,请参阅Matplotlib 应用程序接口 (APIs)。
在显式面向对象 (OO) 接口中,我们直接使用 axes.Axes
实例来在 figure.Figure
实例中构建可视化。在受 MATLAB 启发并建模的隐式接口中,我们使用一个全局状态的接口,该接口封装在 pyplot
模块中,用于在“当前 Axes”上绘图。有关 pyplot 接口的更深入了解,请参阅 pyplot 教程。
大多数术语都很直观,但需要记住的关键点是:
我们直接从 Axes 调用绘图方法,这使我们在定制绘图时拥有更大的灵活性和能力。
注意
通常,在绘图时使用显式接口而不是隐式 pyplot 接口。
我们的数据#
我们将使用本教程所源自的文章中的数据。它包含了多家公司的销售信息。
import matplotlib.pyplot as plt
import numpy as np
data = {'Barton LLC': 109438.50,
'Frami, Hills and Schmidt': 103569.59,
'Fritsch, Russel and Anderson': 112214.71,
'Jerde-Hilpert': 112591.43,
'Keeling LLC': 100934.30,
'Koepp Ltd': 103660.54,
'Kulas Inc': 137351.96,
'Trantow-Barrows': 123381.38,
'White-Trantow': 135841.99,
'Will LLC': 104437.60}
group_data = list(data.values())
group_names = list(data.keys())
group_mean = np.mean(group_data)
开始使用#
这些数据很自然地可以可视化为条形图,每组一个条形。要使用面向对象的方法实现这一点,我们首先生成一个 figure.Figure
实例和一个 axes.Axes
实例。Figure 就像一块画布,而 Axes 则是这块画布上我们将进行特定可视化的部分。
注意
一个 Figure 可以包含多个 Axes。有关如何实现此目的的信息,请参阅 紧凑布局教程。
fig, ax = plt.subplots()

现在我们已经有了一个 Axes 实例,我们可以在其上进行绘图了。
fig, ax = plt.subplots()
ax.barh(group_names, group_data)

控制样式#
Matplotlib 提供了许多样式,以便您可以根据需求定制可视化。要查看样式列表,我们可以使用 style
模块。
print(plt.style.available)
['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'petroff10', 'seaborn-v0_8', 'seaborn-v0_8-bright', 'seaborn-v0_8-colorblind', 'seaborn-v0_8-dark', 'seaborn-v0_8-dark-palette', 'seaborn-v0_8-darkgrid', 'seaborn-v0_8-deep', 'seaborn-v0_8-muted', 'seaborn-v0_8-notebook', 'seaborn-v0_8-paper', 'seaborn-v0_8-pastel', 'seaborn-v0_8-poster', 'seaborn-v0_8-talk', 'seaborn-v0_8-ticks', 'seaborn-v0_8-white', 'seaborn-v0_8-whitegrid', 'tableau-colorblind10']
您可以使用以下方式激活样式
plt.style.use('fivethirtyeight')
现在让我们重新制作上述图表,看看它的外观
fig, ax = plt.subplots()
ax.barh(group_names, group_data)

样式控制着许多方面,例如颜色、线宽、背景等。
定制绘图#
现在我们已经得到了一个具有我们想要的一般外观的图表,接下来让我们对其进行微调,使其可以打印。首先,让我们旋转 x 轴上的标签,使其显示更清晰。我们可以通过 axes.Axes.get_xticklabels()
方法获取这些标签。
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()

如果想一次性设置多个项目的属性,使用 pyplot.setp()
函数会很有用。它将接受一个(或多个)Matplotlib 对象列表,并尝试设置每个对象的一些样式元素。
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

看起来这会切掉底部的一些标签。我们可以告诉 Matplotlib 自动为我们创建的图表中的元素留出空间。为此,我们设置 rcParams 的 autolayout
值。有关使用样式表和 rcParams 控制绘图样式、布局和其他功能的更多信息,请参阅 使用样式表和 rcParams 定制 Matplotlib。
plt.rcParams.update({'figure.autolayout': True})
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

接下来,我们向绘图添加标签。要使用 OO 接口执行此操作,我们可以使用 Artist.set()
方法来设置此 Axes 对象的属性。
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')

我们还可以使用 pyplot.subplots()
函数调整此绘图的大小。我们可以通过 figsize 关键字参数来完成。
注意
虽然 NumPy 中的索引遵循 (行, 列) 的形式,但 figsize 关键字参数遵循 (宽度, 高度) 的形式。这符合可视化中的约定,但不幸的是,这与线性代数中的约定不同。
fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')

对于标签,我们可以以函数的形式指定自定义格式设置指南。下面我们定义一个函数,它接受一个整数作为输入,并返回一个字符串作为输出。当与 Axis.set_major_formatter
或 Axis.set_minor_formatter
一起使用时,它们将自动创建并使用 ticker.FuncFormatter
类。
对于此函数,x
参数是原始刻度标签,pos
是刻度位置。这里我们只使用 x
,但两个参数都是必需的。
def currency(x, pos):
"""The two arguments are the value and tick position"""
if x >= 1e6:
s = f'${x*1e-6:1.1f}M'
else:
s = f'${x*1e-3:1.0f}K'
return s
然后我们可以将此函数应用于图表上的标签。为此,我们使用 Axes 的 xaxis
属性。这使您可以在图表上的特定轴上执行操作。
fig, ax = plt.subplots(figsize=(6, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(currency)

组合多个可视化#
可以在同一个 axes.Axes
实例上绘制多个绘图元素。为此,我们只需在该 Axes 对象上调用另一个绘图方法即可。
fig, ax = plt.subplots(figsize=(8, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
# Add a vertical line, here we set the style in the function call
ax.axvline(group_mean, ls='--', color='r')
# Annotate new companies
for group in [3, 5, 8]:
ax.text(145000, group, "New Company", fontsize=10,
verticalalignment="center")
# Now we move our title up since it's getting a little cramped
ax.title.set(y=1.05)
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(currency)
ax.set_xticks([0, 25e3, 50e3, 75e3, 100e3, 125e3])
fig.subplots_adjust(right=.1)
plt.show()

保存绘图#
现在我们对绘图结果很满意,我们想将其保存到磁盘。Matplotlib 支持多种文件格式。要查看可用选项列表,请使用:
print(fig.canvas.get_supported_filetypes())
{'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format', 'webp': 'WebP Image Format'}
然后我们可以使用 figure.Figure.savefig()
将图表保存到磁盘。请注意,下面展示了几个有用的标志参数:
transparent=True
:如果格式支持,则使保存的图表背景透明。dpi=80
:控制输出的分辨率(每平方英寸点数)。bbox_inches="tight"
:使图表边界与我们的绘图紧密贴合。
# Uncomment this line to save the figure.
# fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")
脚本总运行时间: (0 分 3.734 秒)