matplotlib绘制图标教学
时间: 2025-06-20 09:42:44 浏览: 13
### 使用 Matplotlib 绘制图表教程
Matplotlib 是一个强大的 Python 数据可视化工具,能够帮助用户轻松绘制各种类型的图表。以下是几个常见的图表类型及其对应的代码示例。
#### 1. 折线图
折线图是一种常用的图表形式,适合用来展示连续变量的变化趋势。
```python
import matplotlib.pyplot as plt
# 准备数据
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# 创建画布和坐标系
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(x, y)
# 添加标题和标签
ax.set_title('Line Chart Example')
ax.set_xlabel('X-axis Label')
ax.set_ylabel('Y-axis Label')
# 显示图形
plt.show()
```
#### 2. 子图 (Subplots)
当需要在同一张图像中显示多个图表时,可以使用 `subplots` 方法创建子图。
```python
import matplotlib.pyplot as plt
# 创建两个子图
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
# 在第一个子图上绘制折线图
axes[0].plot([1, 2, 3], [4, 5, 6])
axes[0].set_title('First Subplot')
# 在第二个子图上绘制柱状图
axes[1].bar(['A', 'B', 'C'], [7, 8, 9])
axes[1].set_title('Second Subplot')
# 调整布局以防止重叠
plt.tight_layout()
# 显示图形
plt.show()
```
#### 3. 箱线图
箱线图用于分析数据的分布情况以及检测异常值。
```python
import matplotlib.pyplot as plt
import numpy as np
# 随机生成四组数据
np.random.seed(42)
data = np.random.normal(size=(100, 4), loc=0, scale=1.5)
# 创建画布和坐标系
fig, ax = plt.subplots()
# 绘制箱线图
ax.boxplot(data, notch=True, sym='o', vert=True, whis=1.5)
# 设置标题和标签
ax.set_title('Box Plot Example', fontsize=16)
ax.set_xlabel('Groups', fontsize=14)
ax.set_ylabel('Values', fontsize=14)
# 显示图形
plt.show()
```
#### 4. 等高线图
等高线图适用于二维空间中的函数可视化。
```python
import matplotlib.pyplot as plt
import numpy as np
# 定义网格范围
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
# 计算 Z 值
Z = np.sqrt(X**2 + Y**2)
# 绘制等高线图
plt.contourf(X, Y, Z, levels=20, cmap='viridis')
# 添加颜色条
plt.colorbar(label='Contour Levels')
# 设置标题和标签
plt.title('Contour Plot Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# 显示图形
plt.show()
```
#### 5. 三维图
通过引入 `mpl_toolkits.mplot3d` 模块,可以在 Matplotlib 中绘制三维图形。
```python
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
# 定义网格范围
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
# 计算 Z 值
Z = np.sin(np.sqrt(X**2 + Y**2)) / (np.sqrt(X**2 + Y**2))
# 创建三维图形对象
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制表面图
surf = ax.plot_surface(X, Y, Z, cmap='coolwarm')
# 添加颜色条
fig.colorbar(surf, shrink=0.5, aspect=5)
# 设置标题和标签
ax.set_title('3D Surface Plot Example')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
# 显示图形
plt.show()
```
以上展示了如何利用 Matplotlib 进行基本的数据可视化操作[^1]。这些例子涵盖了从简单的折线图到复杂的三维图形的各种场景。
阅读全文
相关推荐
















