Python:Matplotlib

Matplotlib相关的核心内容

1. Matplotlib概述

Matplotlib是Python的2D绘图库,能够生成高质量的静态、交互式和动画可视化效果。其核心特点是:

  • 层次结构:基于Figure(画布)和Axes(坐标系)的层级对象模型。
  • 灵活性:支持从简单折线图到复杂3D图形的多种图表类型。
  • 兼容性:与NumPy、Pandas无缝集成,支持输出多种格式(PNG、PDF、SVG等)。
 Matplotlib 的核心设计理念

Matplotlib 采用分层对象模型,核心对象分为四个层级:

  1. Figure(画布)​:所有内容的容器,相当于一张白纸。
  2. Axes(坐标系)​:真正绘制数据的区域,包含坐标轴、标题、图例等。
  3. Axis(坐标轴)​:控制数据范围的显示(如 X 轴和 Y 轴)。
  4. Artist(元素)​:所有可见对象(如线条、文本、标记)的基类。
import matplotlib.pyplot as plt

# 创建 Figure 和 Axes
fig = plt.figure(figsize=(6, 4))  # 画布尺寸:宽6英寸,高4英寸
ax = fig.add_subplot(1, 1, 1)    # 添加一个子图

2.两种绘图接口

Matplotlib 提供两种主要绘图方式:

(1) Pyplot 快捷接口(面向脚本)​

快速绘制简单图表,适合交互式环境(如 Jupyter Notebook):

plt.plot([1, 2, 3, 4], [10, 20, 15, 25], 'ro--')  # 红色圆圈虚线
plt.title("Simple Line Chart")
plt.xlabel("X-axis")
plt.show()
(2) 面向对象接口(推荐)​

更灵活,适用于复杂图表:

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [10, 20, 15, 25], marker='o', linestyle='--', color='blue')
ax.set_title("Advanced Line Chart")
ax.set_xlabel("X-axis")
ax.grid(True)
plt.show()

​3. 核心概念

(1) Figure(画布)​
  • 所有图表的容器,相当于一张白纸。
  • 创建方法:
    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(8, 6))  # 设置画布大小
(2) Axes(坐标系)​
  • 实际的图表区域,包含坐标轴、标签、数据等。
  • 创建方法:
    ax = fig.add_subplot(1, 1, 1)  # 1行1列的第1个子图
(3) Axis(坐标轴)​
  • 控制数据的显示范围(如ax.set_xlim(0, 10))。
(4) Artist(元素)​
  • 所有可见元素(如线条、文本、标记)的基类。
(5) Backend(后端)​
  • 控制渲染方式(如Agg用于生成图片,Tkinter用于交互式窗口)。

 4.核心绘图流程

步骤 1:创建 Figure 和 Axes
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
步骤 2:绘制数据
# 示例:绘制折线图、散点图和柱状图
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]

ax.plot(x, y, label='Line')        # 折线图
ax.scatter(x, y, label='Points')   # 散点图
ax.bar(x, y, alpha=0.3, label='Bars')  # 柱状图(半透明)
步骤 3:自定义样式
ax.set_title("Combined Plot", fontsize=14)
ax.set_xlabel("X-axis", fontsize=12)
ax.set_ylabel("Y-axis", fontsize=12)
ax.legend(loc='upper left')        # 显示图例
ax.grid(linestyle='--', alpha=0.5) # 虚线网格
步骤 4:保存或显示图表
plt.savefig('plot.png', dpi=300, bbox_inches='tight')  # 保存为高分辨率图片
plt.show()  # 显示图表

5. 常用图表类型

(1) 折线图(Line Plot)​
ax.plot(x, y, color='red', linewidth=2, linestyle='--', marker='o')
(2) 散点图(Scatter Plot)​
ax.scatter(x, y, s=50, c='blue', edgecolor='black', alpha=0.7)
(3) 柱状图(Bar Chart)​
ax.bar(categories, values, color='green', width=0.5, edgecolor='black')
(4) 直方图(Histogram)​
ax.hist(data, bins=30, density=True, color='orange', alpha=0.7)
(5) 箱线图(Boxplot)​
ax.boxplot([data1, data2], vert=True, patch_artist=True)
基本绘图(法二)

(1) 折线图

x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.plot(x, y, color='blue', linestyle='--', marker='o', label='Data')
plt.title("Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()  # 显示图例
plt.grid(True)
plt.show()

(2) 散点图

plt.scatter(x, y, s=100, c='red', alpha=0.5, label='Points')
plt.title("Scatter Plot")

(3) 柱状图

categories = ['A', 'B', 'C']
values = [30, 50, 20]
plt.bar(categories, values, color='green', width=0.5)

(4) 直方图

data = np.random.randn(1000)
plt.hist(data, bins=30, edgecolor='black')


​6. 自定义图表

(1) 标题与标签
ax.set_title("My Plot", fontsize=14)
ax.set_xlabel("X Label", fontsize=12)
ax.set_ylabel("Y Label", fontsize=12)
​(2) 图例与网格
ax.legend(loc='upper right', frameon=False)  # 无边框图例
ax.grid(linestyle=':', alpha=0.7)  # 虚线网格
​(3) 颜色与样式
  • 简写格式plt.plot(x, y, 'ro--') 表示红色圆圈虚线。
  • RGB颜色color=(0.2, 0.5, 0.8)
  • 坐标轴范围
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 30)

7.高级功能

1. ​多子图布局
  • 网格布局
    fig, axs = plt.subplots(2, 2, figsize=(12, 8))
    axs[0, 0].plot(x, y)        # 第一行第一列
    axs[1, 1].hist(np.random.randn(1000), bins=30)  # 第二行第二列
  • 复杂布局​(使用 GridSpec):
    import matplotlib.gridspec as gridspec
    fig = plt.figure()
    gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2])
    ax1 = fig.add_subplot(gs[0, :])  # 跨两列
    ax2 = fig.add_subplot(gs[1, 0])
2. ​颜色与样式
  • 预定义样式
    plt.style.use('ggplot')  # 其他选项:seaborn, fivethirtyeight
  • 颜色映射(Colormap)​
    scatter = ax.scatter(x, y, c=np.random.rand(len(x)), cmap='viridis')
    plt.colorbar(scatter, label='Value')  # 添加颜色条
3. ​注释与标注
ax.annotate('Peak', xy=(3, 25), xytext=(3.5, 28),
            arrowprops=dict(facecolor='black', arrowstyle='->'))
ax.text(1, 20, 'Important Point', fontsize=12, color='red')
4. ​双坐标轴
ax2 = ax.twinx()  # 共享X轴,创建第二个Y轴
ax.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b--')
5. 3D绘图
from mpl_toolkits.mplot3d import Axes3D
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='plasma')
6.动画
from matplotlib.animation import FuncAnimation
def update(frame):
    line.set_ydata(np.sin(x + frame/10))
ani = FuncAnimation(fig, update, frames=100, interval=50)

 ​8. 样式与主题

(1) 内置样式
plt.style.use('ggplot')  # 使用ggplot风格
(2) 自定义颜色映射
plt.scatter(x, y, c=z, cmap='viridis')
plt.colorbar()  # 显示颜色条

9. 总结

  • 核心对象Figure > Axes > Axis > Artist
  • 工作流程:创建画布 → 添加子图 → 绘制数据 → 自定义样式 → 保存或显示。
  • 最佳实践:优先使用面向对象接口(如ax.plot()),而非pyplot函数。
实战技巧
  1. 避免绘图重叠:在 Jupyter 中运行 %matplotlib inline 后,使用 plt.close() 清除内存中的图表。
  2. 处理中文显示
    plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows
    plt.rcParams['axes.unicode_minus'] = False    # 解决负号显示问题
  3. 动态更新图表:在循环中使用 plt.pause(0.1) 实现简单动画。
  4. 结合Pandas使用
    import pandas as pd
    df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 1]})
    df.plot(x='x', y='y', kind='line', ax=ax)  # 直接使用DataFrame绘图

 

你可能感兴趣的:(python基础与机器学习,python,matplotlib,开发语言)