Matplotlib


官方文档 (https://matplotlib.org/stable/contents.html)


1. 安装与环境配置

pip install matplotlib

推荐配合使用:

pip install numpy pandas  # 数据处理常用库

2. 核心概念

  • Figure: 画布/绘图板(顶级容器)
  • Axes: 坐标系(包含坐标轴、标题、数据等的绘图区域)
  • Axis: 坐标轴(控制数据范围、刻度等)
  • Artist: 所有可见元素的基类

3. 基本绘图流程

import matplotlib.pyplot as plt
import numpy as np

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

# 创建图形和坐标系
fig, ax = plt.subplots()

# 绘制数据
ax.plot(x, y, label='sin(x)')

# 添加装饰元素
ax.set_title("Sine Wave")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.legend()
ax.grid(True)

# 显示/保存图形
plt.show()
# fig.savefig('sine_wave.png', dpi=300)

4. 常见图表类型

4.1 折线图

plt.plot(x, y, color='red', linestyle='--', linewidth=2)

4.2 散点图

x = np.random.randn(100)
y = x + np.random.randn(100)*0.5
plt.scatter(x, y, 
           c=np.arctan2(y, x),  # 颜色映射
           s=100,               # 点大小
           alpha=0.7, 
           cmap='viridis')
plt.colorbar()

4.3 条形图

labels = ['A', 'B', 'C']
values = [25, 40, 63]

# 垂直条形图
plt.bar(labels, values, color=['#ff9999','#66b3ff','#99ff99'])

# 水平条形图
plt.barh(labels, values)

4.4 直方图

data = np.random.randn(1000)
plt.hist(data, 
         bins=30, 
         density=True, 
         cumulative=False,
         histtype='stepfilled')

4.5 饼图

sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # 突出显示第二块
plt.pie(sizes, 
        explode=explode,
        labels=['A', 'B', 'C', 'D'],
        autopct='%1.1f%%',
        startangle=90)
plt.axis('equal')  # 保持圆形

4.6 箱线图

data = [np.random.normal(0, std, 100) for std in range(1, 4)]
plt.boxplot(data, 
           vert=True, 
           patch_artist=True,
           labels=['Set 1', 'Set 2', 'Set 3'])

4.7 热力图

data = np.random.rand(10, 10)
plt.imshow(data, cmap='hot')
plt.colorbar()

5. 样式与自定义

5.1 颜色/线型/标记

# 简写参数:fmt = '[marker][line][color]'
plt.plot(x, y, 'ro--')          # 红色圆圈,虚线
plt.plot(x, y, color='#FF00FF',  # HEX颜色
        linestyle=':', 
        linewidth=3,
        marker='s',             # 方块标记
        markersize=8,
        markerfacecolor='white',
        markeredgecolor='black')

5.2 图例设置

plt.legend(loc='upper right',     # 位置
          frameon=False,         # 无边框
          ncol=2,               # 分列显示
          title='Legend Title')

5.3 网格与背景

ax.grid(True, 
       which='both',           # 主/次刻度都显示网格
       linestyle='--', 
       alpha=0.7)
ax.set_facecolor('#f0f0f0')    # 坐标系背景色
fig.patch.set_facecolor('white') # 画布背景色

5.4 字体与文本

plt.xlabel("X Label", 
         fontsize=14, 
         fontweight='bold',
         color='navy')
plt.title("Customized Title", 
        fontfamily='serif',
        fontstyle='italic')

6. 多子图布局

6.1 subplot

plt.subplot(2, 2, 1)  # 2行2列,第1个位置
plt.plot(x, y)
plt.subplot(2, 2, 4)  # 第4个位置
plt.scatter(x, y)

6.2 subplots

fig, axs = plt.subplots(nrows=2, 
                       ncols=2, 
                       figsize=(10, 8),
                       sharex=True)
axs[0,0].plot(x, y)
axs[1,1].hist(data)

6.3 GridSpec(复杂布局)

import matplotlib.gridspec as gridspec

fig = plt.figure()
gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[4, 1])

ax1 = fig.add_subplot(gs[0, :])  # 首行全宽
ax2 = fig.add_subplot(gs[1, 0])
ax3 = fig.add_subplot(gs[1, 1])

7. 高级功能

7.1 交互模式

plt.ion()  # 开启交互模式
# 动态更新图表...
plt.ioff() # 关闭交互模式

7.2 动画

from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
line, = ax.plot([], [])

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return line,

def update(frame):
    x = np.linspace(0, 2*np.pi, 100)
    y = np.sin(x + frame/10)
    line.set_data(x, y)
    return line,

ani = FuncAnimation(fig, update, frames=100, init_func=init, blit=True)
plt.show()

7.3 3D绘图

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_zlabel('Z Axis')

8. 最佳实践

  1. 避免过度装饰:保持图表简洁易读

  2. 选择合适的图表类型

  3. 趋势展示 → 折线图

  4. 分布比较 → 箱线图/直方图
  5. 比例关系 → 饼图/堆叠条形图

  6. 调整布局

python plt.tight_layout() # 自动调整子图间距

  1. 高质量输出

python fig.savefig('output.png', dpi=300, bbox_inches='tight', transparent=True)

  1. 样式预设

python plt.style.use('ggplot') # 使用内置样式 # 可用样式:'seaborn', 'fivethirtyeight', 'dark_background' 等

常见问题解决:

  • 图形不显示:确保最后调用了 plt.show()

  • 中文乱码:设置中文字体

python plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题

0 条评论

发表评论

暂无评论,欢迎发表您的观点!