ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 1. Matplotlib 核心特点
  • 2. 基本使用
    • 2.1 基本绘图流程
    • 2.2 常用图表类型
  • 3. 图形定制
    • 3.1 样式设置
    • 3.2 多子图布局
    • 3.3 高级布局
  • 4. 高级功能
    • 4.1 3D 绘图
    • 4.2 动画
    • 4.3 样式表
  • 5. 实用技巧
    • 5.1 保存图形
    • 5.2 LaTeX 支持
    • 5.3 颜色映射
  • 6. 与 Pandas 集成
  • 7. 学习资源

Matplotlib 是 Python 最基础、最广泛使用的 2D 绘图库,提供了类似 MATLAB 的绘图接口,是科学计算和数据分析领域的重要工具。

1. Matplotlib 核心特点 #

  1. 基础性强:Python 数据可视化的基础库,许多其他库(如 Seaborn)基于它构建
  2. 高度可定制:几乎可以控制图形的每一个元素
  3. 多种输出格式:支持 PNG、PDF、SVG 等多种格式
  4. 多种接口:提供 MATLAB 风格的 pyplot 接口和面向对象接口
  5. 跨平台:支持 Windows、Linux 和 macOS

2. 基本使用 #

2.1 基本绘图流程 #

这是Matplotlib 最基础的绘图流程,包括数据创建、图形和坐标轴的生成、曲线绘制、标题和标签设置、图例添加以及图形显示。适用于所有基础可视化场景。

# 导入 Matplotlib 的 pyplot 接口
import matplotlib.pyplot as plt
# 导入 NumPy 用于数值计算
import numpy as np

# 创建自变量数据,等间隔100个点
x = np.linspace(0, 10, 100)
# 计算因变量,正弦函数
y = np.sin(x)

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

# 绘制曲线,label用于图例
ax.plot(x, y, label='sin(x)')

# 设置图形标题
ax.set_title("Sine Wave")
# 设置x轴标签
ax.set_xlabel("x")
# 设置y轴标签
ax.set_ylabel("sin(x)")

# 添加图例
ax.legend()

# 显示图形
plt.show()

2.2 常用图表类型 #

本段代码展示了 Matplotlib 支持的多种常用图表类型,包括折线图、散点图、柱状图、直方图、饼图和箱线图,适用于不同的数据可视化需求。

# 折线图,适合趋势展示
plt.plot(x, y)

# 散点图,适合相关性分析
plt.scatter(x, y)

# 柱状图,适合分类数据对比
plt.bar(categories, values)

# 直方图,适合分布分析
plt.hist(data, bins=30)

# 饼图,适合比例展示
plt.pie(sizes, labels=labels)

# 箱线图,适合统计分布和异常值分析
plt.boxplot(data)

3. 图形定制 #

3.1 样式设置 #

本段代码演示了如何自定义线条、散点和柱状图的样式,包括线型、颜色、标记、透明度等,提升图表的美观性和可读性。

# 线条样式设置,虚线、加粗、红色、圆点标记
plt.plot(x, y, linestyle='--', linewidth=2, color='red', marker='o', markersize=8)

# 散点样式设置,点大小、颜色、透明度、边框色
plt.scatter(x, y, s=100, c=colors, alpha=0.5, edgecolors='black')

# 柱状图样式设置,宽度、底部、对齐方式
plt.bar(x, height, width=0.8, bottom=None, align='center')

3.2 多子图布局 #

本段代码演示了如何使用 subplots 创建多子图网格,并在不同子图上绘制不同类型的图表,适合多视图对比分析。

# 创建2行2列的子图网格,设置画布大小
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))

# 在第1个子图绘制折线图
axes[0, 0].plot(x, y)
# 在第2个子图绘制散点图
axes[0, 1].scatter(x, y)
# 在第3个子图绘制直方图
axes[1, 0].hist(data)
# 在第4个子图绘制箱线图
axes[1, 1].boxplot(data)

# 自动调整子图间距,防止重叠
plt.tight_layout()

3.3 高级布局 #

本段代码演示了如何使用 GridSpec 实现复杂的子图布局,支持不同的行列比例和灵活的子图位置。

# 导入 GridSpec 工具
import matplotlib.gridspec as gridspec

# 创建画布并设置大小
fig = plt.figure(figsize=(10, 8))
# 创建2x2的网格,设置宽高比
gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[2, 1])

# 在不同网格位置创建子图
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
ax4 = plt.subplot(gs[3])

4. 高级功能 #

4.1 3D 绘图 #

本段代码演示了如何使用 Matplotlib 进行3D绘图,包括3D散点图和3D曲面图,适用于空间数据可视化。

# 导入3D绘图工具包
from mpl_toolkits.mplot3d import Axes3D

# 创建画布对象
fig = plt.figure()
# 添加3D坐标轴
ax = fig.add_subplot(111, projection='3d')

# 3D散点图,x、y、z为三维坐标
ax.scatter(x, y, z)

# 生成网格数据,用于3D曲面
X, Y = np.meshgrid(x, y)
# 绘制3D曲面图,cmap设置颜色映射
ax.plot_surface(X, Y, Z, cmap='viridis')

4.2 动画 #

本段代码演示了如何用 FuncAnimation 创建动态动画,适合演示数据随时间变化的过程。

# 导入动画工具
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):
    line.set_data(x[:frame], y[:frame])
    return line,

# 创建动画对象,blit加速渲染
ani = FuncAnimation(fig, update, frames=len(x), init_func=init, blit=True)
# 显示动画
plt.show()

4.3 样式表 #

本段代码演示了如何使用 Matplotlib 的样式表快速切换图表风格,提升美观性和一致性。

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

# 使用ggplot风格
plt.style.use('ggplot')
# 组合使用多个样式
plt.style.use(['dark_background', 'fast'])

5. 实用技巧 #

5.1 保存图形 #

本段代码演示了如何将 Matplotlib 图形保存为不同格式的图片文件,支持 PNG、PDF、SVG 等,适合成果输出和报告插图。

# 保存为PNG图片,设置分辨率和边距
plt.savefig('figure.png', dpi=300, bbox_inches='tight')

# 保存为PDF格式
plt.savefig('figure.pdf')
# 保存为SVG矢量图
plt.savefig('figure.svg')

5.2 LaTeX 支持 #

本段代码演示了如何在标题和坐标轴标签中使用 LaTeX 数学公式,提升学术排版效果。

# 在标题中使用LaTeX公式
plt.title(r'$\alpha > \beta$')
# 在x轴标签中使用分式公式
plt.xlabel(r'$\frac{x}{y}$')

5.3 颜色映射 #

本段代码演示了如何为散点图添加颜色映射和颜色条,适合展示第三变量的分布。

# 绘制带颜色映射的散点图
sc = plt.scatter(x, y, c=z, cmap='viridis')
# 添加颜色条
plt.colorbar(sc)

6. 与 Pandas 集成 #

本段代码演示了如何直接用 Pandas DataFrame 绘图,以及如何分组绘制多类数据,适合数据分析与可视化一体化场景。

# 导入 pandas 库
import pandas as pd

# 创建包含三列的数据框
# x、y为正态分布,category为三类标签
df = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'category': np.random.choice(['A', 'B', 'C'], 100)
})

# 直接用DataFrame绘制散点图
# kind参数指定图类型
# x、y为坐标轴
df.plot(x='x', y='y', kind='scatter')

# 按类别分组绘制散点图
for name, group in df.groupby('category'):
    # 每一类分别绘制
    plt.scatter(group['x'], group['y'], label=name)
# 添加图例
plt.legend()

7. 学习资源 #

  1. 官方文档:https://matplotlib.org/stable/contents.html
  2. 图表示例库:https://matplotlib.org/stable/gallery/index.html
  3. Matplotlib 教程:https://matplotlib.org/stable/tutorials/index.html

访问验证

请输入访问令牌

Token不正确,请重新输入