按 Y 值设置颜色

PythonPythonBeginner
立即练习

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

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

简介

Matplotlib 是 Python 中的一个数据可视化库。它是创建各种图形和图表的强大工具。Matplotlib 的特性之一是能够根据 y 值绘制不同颜色的线条。本实验将演示如何使用掩码数组根据 y 值绘制不同颜色的线条。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 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/line_plots("Line Plots") 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-48605{{"按 Y 值设置颜色"}} matplotlib/figures_axes -.-> lab-48605{{"按 Y 值设置颜色"}} matplotlib/line_plots -.-> lab-48605{{"按 Y 值设置颜色"}} python/tuples -.-> lab-48605{{"按 Y 值设置颜色"}} python/importing_modules -.-> lab-48605{{"按 Y 值设置颜色"}} python/numerical_computing -.-> lab-48605{{"按 Y 值设置颜色"}} python/data_visualization -.-> lab-48605{{"按 Y 值设置颜色"}} end

导入所需库

在这一步中,我们将导入本实验所需的库。

import matplotlib.pyplot as plt
import numpy as np

创建数据

在这一步中,我们将为绘图创建数据。我们将创建一个t值的数组和一个s值的数组。

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)

创建掩码数组

在这一步中,我们将创建三个掩码数组:一个用于大于某个阈值的值,一个用于小于某个阈值的值,还有一个用于介于两个阈值之间的值。

upper = 0.77
lower = -0.77

supper = np.ma.masked_where(s < upper, s)
slower = np.ma.masked_where(s > lower, s)
smiddle = np.ma.masked_where((s < lower) | (s > upper), s)

创建绘图

在这一步中,我们将使用上一步创建的掩码数组来创建绘图。我们将分别绘制每个掩码数组,并为每个数组使用不同的颜色。

fig, ax = plt.subplots()
ax.plot(t, smiddle, t, slower, t, supper)
plt.show()

总结

在本实验中,我们学习了如何在Matplotlib中使用掩码数组根据y值绘制不同颜色的线条。当可视化具有不同感兴趣区域的数据时,此技术有助于清晰区分不同区域,非常实用。