创建折线图

PythonPythonBeginner
立即练习

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

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

简介

在本实验中,我们将学习如何使用 Python Matplotlib 创建折线图。折线图是一种在直线上显示数据点的方式。它用于展示特定数据集随时间的趋势。

虚拟机使用提示

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

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

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

导入库

首先,我们需要导入必要的库。我们将使用 matplotlib.pyplot 库来创建折线图。

import matplotlib.pyplot as plt
import numpy as np

创建数据

接下来,我们需要创建一些要绘制在折线上的数据。我们将使用 NumPy 为我们的折线创建一些随机数据点。

x = np.linspace(0, 10)

创建折线图

现在我们可以使用 matplotlib.pyplot 中的 plot() 函数来创建折线图。我们将使用 Solarized Light 配色方案中的不同颜色绘制 8 条随机折线。

with plt.style.context('Solarize_Light2'):
    plt.plot(x, np.sin(x) + x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 2 * x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 3 * x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 4 + np.random.randn(50))
    plt.plot(x, np.sin(x) + 5 * x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 6 * x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 7 * x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 8 * x + np.random.randn(50))

添加标签和标题

我们可以使用 xlabel()ylabel()title() 函数为折线图添加标签和标题。

plt.title('8 Random Lines - Line')
plt.xlabel('x label', fontsize=14)
plt.ylabel('y label', fontsize=14)

显示图表

最后,我们可以使用 show() 函数来显示我们的折线图。

plt.show()

总结

在本实验中,我们学习了如何使用 Python 的 Matplotlib 创建折线图。我们导入了必要的库,创建了一些数据,并使用 plot() 函数创建了折线图。我们为图表添加了标签和标题,并使用 show() 函数进行显示。