为 Matplotlib 绘图添加颜色条

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

Matplotlib 是一个用于数据可视化的 Python 库。在本实验中,我们将学习如何在 Matplotlib 中为绘图添加颜色条。颜色条对于指示颜色映射所代表的值范围很有用。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("Matplotlib")) -.-> matplotlib/BasicConceptsGroup(["Basic Concepts"]) matplotlib(("Matplotlib")) -.-> matplotlib/PlottingDataGroup(["Plotting Data"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/DataScienceandMachineLearningGroup(["Data Science and Machine Learning"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("Importing Matplotlib") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("Understanding Figures and Axes") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("Heatmaps") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48669{{"为 Matplotlib 绘图添加颜色条"}} matplotlib/figures_axes -.-> lab-48669{{"为 Matplotlib 绘图添加颜色条"}} matplotlib/heatmaps -.-> lab-48669{{"为 Matplotlib 绘图添加颜色条"}} python/lists -.-> lab-48669{{"为 Matplotlib 绘图添加颜色条"}} python/tuples -.-> lab-48669{{"为 Matplotlib 绘图添加颜色条"}} python/importing_modules -.-> lab-48669{{"为 Matplotlib 绘图添加颜色条"}} python/data_visualization -.-> lab-48669{{"为 Matplotlib 绘图添加颜色条"}} end

导入必要的库

我们将从导入必要的库开始。我们将使用 Matplotlib 的 pyplot 模块,它提供了创建绘图的接口。

import matplotlib.pyplot as plt

创建一个绘图

接下来,我们将使用 Matplotlib 的 imshow 函数创建一个绘图。此函数在绘图上显示一幅图像。我们还将创建一个带有两个子图的图形。

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.subplots_adjust(wspace=0.5)

im1 = ax1.imshow([[1, 2], [3, 4]])

im2 = ax2.imshow([[1, 2], [3, 4]])

为绘图添加颜色条

现在,我们将使用 Matplotlib 的 make_axes_locatable 函数为每个子图添加颜色条。此函数接受一个现有的坐标轴,将其添加到一个新的 AxesDivider 中,并返回 AxesDivider。然后,可以使用 AxesDividerappend_axes 方法在原始坐标轴的给定一侧(“顶部”、“右侧”、“底部” 或 “左侧”)创建一个新的坐标轴。

ax1_divider = make_axes_locatable(ax1)
cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
cb1 = fig.colorbar(im1, cax=cax1)

ax2_divider = make_axes_locatable(ax2)
cax2 = ax2_divider.append_axes("top", size="7%", pad="2%")
cb2 = fig.colorbar(im2, cax=cax2, orientation="horizontal")
cax2.xaxis.set_ticks_position("top")

显示绘图

最后,我们将使用 Matplotlib 的 show 函数显示绘图。

plt.show()

总结

在本实验中,我们学习了如何在 Matplotlib 中为绘图添加颜色条。我们使用 make_axes_locatable 函数为绘图添加一个额外的坐标轴,并使用 colorbar 函数创建颜色条。我们还学习了如何更改颜色条的方向和位置。