Matplotlib 折线图
最后修改于 2025 年 2 月 25 日
Matplotlib 是一个强大的 Python 库,用于创建静态、动画和交互式可视化。折线图是最常用的图表类型之一,用于显示数据随时间变化的趋势。本教程介绍如何使用 Matplotlib 创建各种类型的折线图。
折线图非常适合可视化连续数据,例如时间序列或趋势。Matplotlib 提供了一个灵活且易于使用的界面,用于创建具有自定义功能的折线图。
基本折线图
此示例演示如何创建基本折线图。
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create a line chart
plt.plot(x, y)
# Add labels and title
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Basic Line Chart")
# Display the chart
plt.show()
plt.plot 函数用于创建折线图。plt.show 函数显示图表。
单个图表中的多条线
此示例展示了如何在单个图表中绘制多条线。
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y1 = [2, 3, 5, 7, 11]
y2 = [1, 4, 6, 8, 10]
# Create multiple lines
plt.plot(x, y1, label="Line 1")
plt.plot(x, y2, label="Line 2")
# Add labels, title, and legend
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Multiple Lines in a Single Chart")
plt.legend()
# Display the chart
plt.show()
label 参数用于区分线条。plt.legend 函数向图表添加图例。
自定义线条样式
此示例演示如何自定义线条样式、颜色和标记。
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create a line chart with custom styles
plt.plot(x, y, linestyle="--", color="green", marker="o", label="Custom Line")
# Add labels, title, and legend
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Custom Line Styles")
plt.legend()
# Display the chart
plt.show()
linestyle、color 和 marker 参数用于自定义线条的外观。
曲线图
这个例子创建了一个平滑的曲线图——特别是一个正弦波——它通常用来表示连续的、周期性的数据,如声波、电信号或物理和工程中的周期性行为。
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2.5 * np.pi * t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('Sine Wave')
plt.grid(True)
plt.savefig('linechart.png')
这个例子创建了一个平滑的曲线图,表示一个正弦波,通常用于模拟周期性现象,如声波或电信号。使用 numpy, 我们生成一个数组 t 表示从 0 到 3 秒的时间值,以 0.01 秒的增量,s 将电压计算为正弦波,在 3 秒内有 2.5 次振荡。plt.plot 函数绘制波形,而标签、标题和网格使图表易于阅读。最后,该图表保存为名为 linechart.png 的图像文件,以供将来使用。
堆叠折线图
该示例可视化了一家公司一年中两条产品线的月收入。
import matplotlib.pyplot as plt
# Months
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# Monthly revenue for two product lines (in $1000s)
product_a = [12, 14, 15, 18, 20, 22, 21, 23, 25, 27, 30, 32]
product_b = [8, 9, 10, 12, 14, 15, 17, 18, 19, 20, 22, 24]
# Total revenue (stacked on top of product A)
total_revenue = [a + b for a, b in zip(product_a, product_b)]
# Plotting revenue for both products
plt.plot(months, product_a, marker='o', label="Product A Revenue")
plt.plot(months, total_revenue, marker='o', label="Total Revenue (A + B)")
# Labels and title
plt.xlabel("Month")
plt.ylabel("Revenue ($1000s)")
plt.title("Monthly Revenue for Product Lines")
plt.legend()
# Display the chart
plt.show()
total_revenue 将 product_b 堆叠在 product_a 的顶部。
面积图
此示例演示如何创建面积图。
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create an area chart
plt.fill_between(x, y, color="skyblue", alpha=0.4)
plt.plot(x, y, color="blue", label="Line")
# Add labels, title, and legend
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Area Chart")
plt.legend()
# Display the chart
plt.show()
plt.fill_between 函数用于填充线条下的区域。alpha 参数控制填充的透明度。
阶梯折线图
阶梯图非常适合显示价格随时间的变化、库存水平或订阅计数等内容——任何保持不变一段时间,然后跳到新值的东西。
我们跟踪一项服务的每月订阅数量,其中用户分批加入。
import matplotlib.pyplot as plt
# Months
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# Subscription count at the end of each month
subscriptions = [100, 150, 150, 200, 250, 300, 300, 350, 400, 400, 450, 500]
# Create a step line chart
plt.step(months, subscriptions, where="mid", label="Subscribers", color="teal")
# Add labels, title, and legend
plt.xlabel("Month")
plt.ylabel("Subscribers")
plt.title("Monthly Subscription Growth")
plt.legend()
# Add grid for clarity
plt.grid(True, linestyle="--", alpha=0.5)
# Display the chart
plt.show()
plt.step 函数创建阶梯折线图。where 参数控制步进位置。
在 x 轴上,我们有一年中的月份。在 y 轴上,我们有订阅计数,这是一个经常以阶梯方式而不是连续变化的东西的例子。where="mid" 使步进变化在视觉上更清晰。
折线图的最佳实践
- 清晰标注轴:始终为 X 轴和 Y 轴添加标签,以使图表易于理解。
- 使用图例: 绘制多条线时添加图例以区分它们。
- 选择合适的颜色: 对多条线使用对比色以提高可读性。
- 限制数据点:避免用过多的数据点使图表混乱。
来源
在本文中,我们探讨了使用 Matplotlib 的各种类型的折线图,包括基本折线图、多条线折线图、堆叠折线图、面积图和阶梯折线图。
作者
列出 所有 Python 教程。