Skip to content

Matplotlib 可视化

Matplotlib 是 Python 中最常用的数据可视化库,支持多种图表类型。

基本绘图

折线图

python
import matplotlib.pyplot as plt
import numpy as np

# 创建数据
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 创建折线图
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linestyle='-', linewidth=2)
plt.title('正弦函数')
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.legend()
plt.grid(True)
plt.show()

散点图

python
# 创建数据
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 100 * np.random.rand(50)

# 创建散点图
plt.figure(figsize=(10, 6))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, label='数据点')
plt.title('散点图')
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.legend()
plt.colorbar(label='颜色值')
plt.show()

柱状图

python
# 创建数据
categories = ['A', 'B', 'C', 'D']
values = [30, 45, 25, 60]

# 创建柱状图
plt.figure(figsize=(10, 6))
plt.bar(categories, values, color=['red', 'blue', 'green', 'yellow'])
plt.title('柱状图')
plt.xlabel('类别')
plt.ylabel('数值')
plt.show()

直方图

python
# 创建数据
data = np.random.randn(1000)

# 创建直方图
plt.figure(figsize=(10, 6))
plt.hist(data, bins=30, color='skyblue', edgecolor='black', alpha=0.7)
plt.title('直方图')
plt.xlabel('数值')
plt.ylabel('频数')
plt.show()

高级绘图

子图

python
# 创建子图
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

# 子图 1: 折线图
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('正弦函数')

# 子图 2: 余弦函数
axes[0, 1].plot(x, np.cos(x))
axes[0, 1].set_title('余弦函数')

# 子图 3: 散点图
axes[1, 0].scatter(np.random.rand(50), np.random.rand(50))
axes[1, 0].set_title('散点图')

# 子图 4: 直方图
axes[1, 1].hist(np.random.randn(100), bins=20)
axes[1, 1].set_title('直方图')

plt.tight_layout()
plt.show()

饼图

python
# 创建数据
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
explode = (0.1, 0, 0, 0)  # 突出显示第一个类别

# 创建饼图
plt.figure(figsize=(8, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=140)
plt.title('饼图')
plt.axis('equal')  # 保证饼图是圆形
plt.show()

箱线图

python
# 创建数据
data = [np.random.normal(0, std, 100) for std in range(1, 4)]

# 创建箱线图
plt.figure(figsize=(10, 6))
plt.boxplot(data, labels=['Group 1', 'Group 2', 'Group 3'])
plt.title('箱线图')
plt.xlabel('组别')
plt.ylabel('数值')
plt.show()

样式设置

使用样式表

python
# 使用预定义样式
plt.style.use('ggplot')

# 查看可用样式
print(plt.style.available)

自定义样式

python
# 创建自定义样式
custom_style = {
    'axes.facecolor': '#f5f5f5',
    'axes.grid': True,
    'grid.color': '#cccccc',
    'axes.edgecolor': '#333333',
    'font.family': 'serif',
    'font.serif': ['Times New Roman'],
    'figure.facecolor': 'white'
}

# 使用自定义样式
plt.rcParams.update(custom_style)

# 绘图
plt.figure(figsize=(10, 6))
plt.plot(x, np.sin(x))
plt.title('自定义样式')
plt.show()

注意事项

  1. 图表清晰度: 确保图表清晰可读,标签和标题明确
  2. 颜色选择: 使用易于区分的颜色,考虑色盲用户
  3. 坐标轴范围: 根据数据调整坐标轴范围
  4. 图表类型选择: 根据数据类型和分析目的选择合适的图表类型