交互式颜色映射调整

PythonPythonBeginner
立即练习

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

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

简介

在本实验中,你将学习如何使用Matplotlib通过颜色条交互式地调整图像上的颜色映射范围。你将使用缩放和平移模式来调整规范的vmin和vmax。使用右键单击进行缩放将按比例扩展vmin和vmax到所选区域。平移时,规范的vmin和vmax都会根据移动方向进行移动。你还可以使用主页/后退/前进按钮回到上一个状态。

虚拟机提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签以访问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/numerical_computing("Numerical Computing") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48610{{"交互式颜色映射调整"}} matplotlib/figures_axes -.-> lab-48610{{"交互式颜色映射调整"}} matplotlib/heatmaps -.-> lab-48610{{"交互式颜色映射调整"}} python/lists -.-> lab-48610{{"交互式颜色映射调整"}} python/tuples -.-> lab-48610{{"交互式颜色映射调整"}} python/importing_modules -.-> lab-48610{{"交互式颜色映射调整"}} python/numerical_computing -.-> lab-48610{{"交互式颜色映射调整"}} python/data_visualization -.-> lab-48610{{"交互式颜色映射调整"}} end

导入所需库

要开始本实验,你需要导入所需的库。在本实验中,我们将使用 matplotlib.pyplotnumpy 库。

import matplotlib.pyplot as plt
import numpy as np

生成数据

接下来,你将生成一些示例数据。在本实验中,我们将生成一个二维正弦波。

t = np.linspace(0, 2 * np.pi, 1024)
data2d = np.sin(t)[:, np.newaxis] * np.cos(t)[np.newaxis, :]

创建绘图

既然你已经生成了数据,接下来将使用 imshow() 函数创建绘图。

fig, ax = plt.subplots()
im = ax.imshow(data2d)
ax.set_title('Pan on the colorbar to shift the color mapping\n'
             'Zoom on the colorbar to scale the color mapping')

添加颜色条

为了交互式地调整颜色映射,你需要使用 colorbar() 函数为绘图添加一个颜色条。

fig.colorbar(im, ax=ax, label='Interactive colorbar')

调整颜色映射

现在,你可以使用颜色条对图像上的颜色映射范围进行交互式调整。你可以通过在颜色条内点击来进行缩放或平移。缩放时,缩放区域的边界框定义了新的规范的 vmin 和 vmax。使用鼠标右键缩放将按比例扩展 vmin 和 vmax 到所选区域。平移时,规范的 vmin 和 vmax 都会根据移动方向进行移动。

显示绘图

最后,你可以使用 show() 函数来显示绘图。

plt.show()

总结

在本实验中,你学习了如何使用Matplotlib通过颜色条对图像上的颜色映射范围进行交互式调整。你使用缩放和平移模式来调整规范的vmin和vmax。使用鼠标右键缩放会按比例扩展vmin和vmax到所选区域。平移时,规范的vmin和vmax都会根据移动方向进行移动。你还学习了如何为绘图添加颜色条以及显示绘图。