简介
在数据可视化中,准确标记坐标轴上的刻度至关重要。Matplotlib 中的 EngFormatter 类能让你使用工程记数法标记坐标轴上的刻度。工程记数法是一种数字的数学表示方法,它使用十的幂次方,且幂次是三的倍数。对于难以用标准记数法读写的大数或小数,这是一种简洁的表达方式。在本实验中,我们将学习如何使用工程记数法标记坐标轴上的刻度。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会立即为你解决问题。
导入所需库
第一步是导入所需的库。在本实验中,我们将使用 Matplotlib、NumPy 和 EngFormatter。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import EngFormatter
创建人工数据
我们需要创建一些用于绘图的人工数据。在本实验中,我们将绘制频率(单位:赫兹)的对数与功率(单位:瓦特)的对数的关系图。我们将使用 numpy 库来生成数据。
## Fixing random state for reproducibility
prng = np.random.RandomState(19680801)
## Create artificial data to plot.
## The x data span over several decades to demonstrate several SI prefixes.
xs = np.logspace(1, 9, 100)
ys = (0.8 + 0.4 * prng.uniform(size=100)) * np.log10(xs)**2
创建图形和子图
我们需要创建一个图形和子图来显示数据。在本实验中,我们将并排创建两个子图。
## Figure width is doubled (2*6.4) to display nicely 2 subplots side by side.
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 9.6))
for ax in (ax0, ax1):
ax.set_xscale('log')
使用工程记数法标记刻度
现在我们将使用工程记数法标记 x 轴上的刻度。在第一个子图中,我们将使用默认设置,在第二个子图中,我们将使用 places 和 sep 选项来指定小数点后的位数以及数字与前缀/单位之间的分隔符。
## Demo of the default settings, with a user-defined unit label.
ax0.set_title('Full unit ticklabels, w/ default precision & space separator')
formatter0 = EngFormatter(unit='Hz')
ax0.xaxis.set_major_formatter(formatter0)
ax0.plot(xs, ys)
ax0.set_xlabel('Frequency')
## Demo of the options `places` (number of digit after decimal point) and
## `sep` (separator between the number and the prefix/unit).
ax1.set_title('SI-prefix only ticklabels, 1-digit precision & '
'thin space separator')
formatter1 = EngFormatter(places=1, sep="\N{THIN SPACE}") ## U+2009
ax1.xaxis.set_major_formatter(formatter1)
ax1.plot(xs, ys)
ax1.set_xlabel('Frequency [Hz]')
显示图表
现在我们将使用 plt.show() 函数来显示图表。
plt.tight_layout()
plt.show()
总结
在本实验中,我们学习了如何使用工程记数法标记轴上的刻度。我们使用了 Matplotlib 中的 EngFormatter 类来标记图表 x 轴上的刻度。我们还学习了如何创建子图,并使用 EngFormatter 的 places 和 sep 选项来自定义刻度标签。工程记数法是一种简洁明了的方式,用于表示用标准记数法难以读写的大数或小数。