Matplotlib零基础入门学习

83 阅读3分钟

前言

由于最近导师的任务分配是训练一个目标识别模型,我最近也是开始学习matplotlib了,以下是一些总结的小知识点

目录

1. 安装与环境配置

安装方式

# 使用 pip
pip install matplotlib

# 使用 conda
conda install matplotlib

依赖检查

import matplotlib
print(matplotlib.__version__)  # 需 >= 3.5.0

2. 基本概念

核心组件

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

两种接口

  1. pyplot 接口(面向过程)
  2. OO 接口(面向对象)

3. 快速入门

基础折线图

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

plt.figure(figsize=(8, 4))  # 创建画布
plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
plt.title("Sine Wave")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)
plt.legend()
plt.show()

Figure_1.png

4. 常见图表类型

4.1 线图 (Line Plot)

plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')

4.2 散点图 (Scatter)

plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, marker='o')

4.3 柱状图 (Bar)

plt.bar(categories, values, color=['r', 'g', 'b'])

4.4 直方图 (Histogram)

plt.hist(data, bins=30, density=True, alpha=0.6)

4.5 饼图 (Pie)

plt.pie(sizes, labels=labels, autopct='%1.1f%%', explode=explode)

4.6 箱线图 (Boxplot)

plt.boxplot([data1, data2], vert=True, patch_artist=True)

5. 自定义与样式调整

颜色与线型

plt.plot(x, y, 
         color='#FF5733',    # 十六进制颜色
         linestyle='-.',    # 线型:'-', '--', '-.', ':'
         linewidth=2, 
         marker='o',
         markersize=8,
         markerfacecolor='white',
         markeredgecolor='black')

样式参数预设

plt.rcParams.update({
    'font.size': 12,
    'axes.titlesize': 16,
    'axes.labelsize': 14,
    'xtick.labelsize': 12,
    'ytick.labelsize': 12,
    'figure.figsize': (10, 6)
})

使用样式表

print(plt.style.available)  # 查看可用样式
plt.style.use('seaborn-darkgrid')

6. 子图与复杂布局

使用 subplot

plt.subplot(2, 1, 1)  # 2行1列第1个
plt.plot(x, y1)
plt.subplot(2, 1, 2)
plt.plot(x, y2)

使用 subplots

fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0,0].plot(x, y1)
axes[1,1].scatter(x, y2)

GridSpec 高级布局

import matplotlib.gridspec as gridspec

gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])  # 首行全宽
ax2 = plt.subplot(gs[1:, 0:2])  # 后两行前两列
ax3 = plt.subplot(gs[1:, 2])

7. 高级技巧

动画制作

from matplotlib.animation import FuncAnimation

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

def animate(i):
    line.set_data(x[:i], y[:i])
    return line,

ani = FuncAnimation(fig, animate, frames=100, interval=50)
plt.show()

3D 图表

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')

交互式图表

from mpld3 import display

display(fig)  # 转换为交互式 HTML

8. 资源推荐

官方文档

优质教程

推荐书籍

  • 《Python数据可视化之美:Matplotlib高级开发指南》
  • 《Matplotlib 3.0 Cookbook》

9. 常见问题

Q1: 图表不显示?

# 非交互环境需要显式调用
plt.show()

# Jupyter 中使用魔法命令
%matplotlib inline

Q2: 中文显示异常?

plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # Mac
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示

Q3: 如何保存高清图片?

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