在 Matplotlib 中绘制多条线


Python 提供了一个名为 Matplotlib 的强大库,该库以图表和图形的形式创建视觉表示。该库的众多功能之一是在单个图形中绘制多条线的能力,这在比较数据集或可视化随时间推移的趋势时非常有用。我们将探讨名为“plot()”的内置方法,该方法用于在 Python Matplotlib 中绘制多条线。

Python 程序在 Matplotlib 中绘制多条线

在直接跳转到程序之前,让我们先熟悉一些 Python 的基本概念,这将有助于我们更好地理解代码。

plot() 方法

此方法用于创建各种类型的绘图,并具有不同的样式和格式。它接受一个或多个表示绘图上 x 和 y 坐标的对。默认情况下,它绘制从一个数据点到另一个数据点的线。但是,我们可以通过更改格式字符串或使用其他参数(如颜色和线型)来绘制其他类型的绘图,例如散点图、条形图和直方图。

语法

plot(x, y)

这里,x 和 y 指定 x 和 y 坐标的数据点。

Numpy

它是 Numerical Python 的简称,用于执行科学计算。它提供对处理大型多维数组和矩阵的支持。我们可以轻松地将其与其他使用数组的 Python 库(如 pandas 和 matplotlib)集成。

字典

它是一个无序且可变的元素集合。它以键值对的形式存储其元素,其中每个键都与一个值相关联。我们可以通过将元素放在花括号“{ }”中作为“键”:“值”来创建字典,并用逗号分隔每个键值对。

示例

Details = {"Tutor" : "Tutorialspoint", "Rank" : 01, "country" : "India"}

示例 1

以下示例说明了在绘制多条线时“plot()”方法的使用。

方法

  • 使用数据点列表初始化三条线。

  • 使用“plot()”方法绘制 x 坐标的值与 y 坐标的值。

  • 然后,使用“title”、“legend”、“xlabel”和“ylabel”添加一些有关绘图的信息。

  • 使用“show()”方法显示结果并退出。

Open Compiler
import matplotlib.pyplot as plt # Data points of line 1 x1 = [1, 2, 3, 4, 5] y1 = [2, 4, 6, 8, 10] # Data points of line 2 x2 = [1, 2, 3, 4, 5] y2 = [1, 3, 5, 7, 9] # Data points of line 3 x3 = [1, 2, 3, 4, 5] y3 = [5, 4, 3, 2, 1] # Plotting all lines with specifying labels plt.plot(x1, y1, label='Line 1') plt.plot(x2, y2, label='Line 2') plt.plot(x3, y3, label='Line 3') # Adding legend, x and y labels, and titles for the lines plt.legend() plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Plotting Multiple Lines') # Displaying the plot plt.show()

输出

示例 2

在此示例中,我们将借助 numpy 和 plot() 方法绘制多条线。在前面示例的相同代码中,我们将使用 numpy 数组而不是列表。

Open Compiler
import numpy as np import matplotlib.pyplot as plt # Data points of line 1 x1 = np.array([1, 2, 3, 4, 5]) y1 = np.array([2, 4, 6, 8, 10]) # Data points of line 2 x2 = np.array([2, 3, 4, 5, 6]) y2 = np.array([1, 3, 5, 7, 9]) # Data points of line 3 x3 = np.array([1, 2, 3, 4, 5]) y3 = np.array([5, 4, 3, 2, 1]) # Plotting all lines with labels plt.plot(x1, y1, label='Line 1') plt.plot(x2, y2, label='Line 2') plt.plot(x3, y3, label='Line 3') # Adding legend, x and y labels, and title for the lines plt.legend() plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Multiple Line Plot') # Displaying the plot plt.show()

输出

示例 3

在以下示例中,我们将借助字典和 plot() 方法绘制多条线。

Open Compiler
import matplotlib.pyplot as plt # Storing the data for line in a Dictionary lines = { 'Line 1': ([1, 2, 3, 4, 5], [4, 5, 6, 8, 10]), 'Line 2': ([1, 2, 3, 4, 5], [1, 3, 5, 7, 9]), 'Line 3': ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) } # Plotting the lines with labels for label, (x, y) in lines.items(): plt.plot(x, y, label = label) # Adding legend, x and y labels, and title for the lines plt.legend() plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Multiple Line Plot') # Displaying the plot plt.show()

输出

结论

我们从介绍 Python 的 Matplotlib 库开始本文,并在后面的部分中学习了“plot()”、numpy 和字典的基本概念,以便更好地理解示例程序。使用这些概念,我们讨论了如何在单个图形中绘制多条线。

更新于: 2023-07-21

7K+ 浏览量

启动你的 职业生涯

通过完成课程获得认证

开始
广告