【AI Study】第五天,Matplotlib(8)- 实用工具

文章概要

本文详细介绍 Matplotlib 的实用工具,包括:

  • 样式表
  • 工具包
  • 导出功能
  • 调试工具

样式表

使用内置样式

import matplotlib.pyplot as plt
import numpy as np

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

# 使用内置样式
plt.style.use('seaborn')
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.title('使用 seaborn 样式')
plt.show()

# 使用多个样式
with plt.style.context(['dark_background', 'seaborn']):
    plt.plot(x, np.cos(x))
    plt.title('使用多个样式')
    plt.show()

创建自定义样式

# 创建自定义样式文件
style_content = '''
axes.grid: True
grid.alpha: 0.3
axes.facecolor: #f0f0f0
axes.edgecolor: #404040
axes.labelcolor: #404040
xtick.color: #404040
ytick.color: #404040
text.color: #404040
font.family: sans-serif
font.sans-serif: Arial, Helvetica, sans-serif
'''

# 保存样式文件
with open('custom_style.mplstyle', 'w') as f:
    f.write(style_content)

# 使用自定义样式
plt.style.use('custom_style')
plt.plot(x, np.sin(x))
plt.title('使用自定义样式')
plt.show()

样式管理

# 获取当前样式
current_style = plt.style.available

# 重置样式
plt.style.use('default')

# 临时使用样式
with plt.style.context('seaborn'):
    plt.plot(x, np.sin(x))
    plt.title('临时使用样式')
    plt.show()

# 合并样式
plt.style.use(['seaborn', 'custom_style'])

工具包

axisartist

from mpl_toolkits.axisartist.axislines import SubplotZero
import numpy as np

# 创建带有零轴的图形
fig = plt.figure(figsize=(8, 6))
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

# 设置轴
ax.axis["xzero"].set_visible(True)
ax.axis["yzero"].set_visible(True)
ax.axis["left"].set_visible(False)
ax.axis["bottom"].set_visible(False)

# 绘制数据
x = np.linspace(-5, 5, 100)
ax.plot(x, np.sin(x))
plt.show()

axes_grid1

from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

# 创建图像网格
fig = plt.figure(figsize=(10, 8))
grid = ImageGrid(fig, 111,
                nrows_ncols=(2, 2),
                axes_pad=0.1,
                share_all=True)

# 在网格中显示图像
for i, ax in enumerate(grid):
    im = ax.imshow(np.random.rand(10, 10))
    ax.set_title(f'Image {i+1}')

plt.colorbar(im, ax=ax.axes_all)
plt.show()

mplot3d

from mpl_toolkits.mplot3d import Axes3D

# 创建 3D 图形
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# 生成数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# 绘制 3D 表面
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
plt.colorbar(surf)
plt.show()

导出功能

保存图片

# 创建图形
fig, ax = plt.subplots(figsize=(8, 6))
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x))

# 保存为不同格式
fig.savefig('figure.png', dpi=300, bbox_inches='tight')
fig.savefig('figure.jpg', quality=95, dpi=300)
fig.savefig('figure.pdf', format='pdf')
fig.savefig('figure.svg', format='svg')

# 设置保存参数
fig.savefig('figure.png',
            dpi=300,                # 分辨率
            bbox_inches='tight',    # 自动调整边界
            pad_inches=0.1,         # 边距
            facecolor='white',      # 背景色
            edgecolor='none',       # 边框颜色
            transparent=False)      # 是否透明

导出 PDF

from matplotlib.backends.backend_pdf import PdfPages

# 创建 PDF 文件
with PdfPages('multipage.pdf') as pdf:
    # 第一页
    fig, ax = plt.subplots(figsize=(8, 6))
    ax.plot(x, np.sin(x))
    ax.set_title('Page 1')
    pdf.savefig(fig)
    plt.close()

    # 第二页
    fig, ax = plt.subplots(figsize=(8, 6))
    ax.plot(x, np.cos(x))
    ax.set_title('Page 2')
    pdf.savefig(fig)
    plt.close()

导出 SVG

# 创建 SVG 图形
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, np.sin(x))

# 保存为 SVG
fig.savefig('figure.svg',
            format='svg',
            dpi=300,
            bbox_inches='tight')

# 设置 SVG 参数
fig.savefig('figure.svg',
            format='svg',
            dpi=300,
            bbox_inches='tight',
            metadata={'Creator': 'Matplotlib',
                     'Title': 'Sine Wave'})

调试工具

图形检查

# 检查图形属性
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, np.sin(x))

# 打印图形信息
print(f'Figure size: {fig.get_size_inches()}')
print(f'Axes limits: {ax.get_xlim()}, {ax.get_ylim()}')
print(f'Number of lines: {len(ax.lines)}')

# 检查图形对象
print(f'Figure DPI: {fig.dpi}')
print(f'Axes position: {ax.get_position()}')
print(f'Line properties: {ax.lines[0].get_properties()}')

性能分析

import time
import cProfile

# 性能测试函数
def plot_performance_test():
    fig, ax = plt.subplots(figsize=(8, 6))
    for i in range(1000):
        ax.plot(x, np.sin(x + i/100))
    plt.close(fig)

# 使用 cProfile 分析
cProfile.run('plot_performance_test()')

# 使用 time 模块
start_time = time.time()
plot_performance_test()
end_time = time.time()
print(f'Execution time: {end_time - start_time:.2f} seconds')

内存分析

import psutil
import os

# 获取当前进程
process = psutil.Process(os.getpid())

# 测量内存使用
def measure_memory():
    # 记录初始内存
    initial_memory = process.memory_info().rss / 1024 / 1024
    
    # 创建图形
    fig, ax = plt.subplots(figsize=(8, 6))
    ax.plot(x, np.sin(x))
    
    # 记录最终内存
    final_memory = process.memory_info().rss / 1024 / 1024
    
    # 计算内存使用
    memory_used = final_memory - initial_memory
    print(f'Memory used: {memory_used:.2f} MB')
    
    plt.close(fig)

measure_memory()

总结

实用工具部分涵盖了:

  1. 样式表(使用内置样式、创建自定义样式、样式管理)
  2. 工具包(axisartist、axes_grid1、mplot3d)
  3. 导出功能(保存图片、导出 PDF、导出 SVG)
  4. 调试工具(图形检查、性能分析、内存分析)

掌握这些实用工具对于提高 Matplotlib 的使用效率至关重要,它可以帮助我们:

  • 统一图形样式
  • 扩展绘图功能
  • 导出高质量图形
  • 优化性能

建议在实际项目中注意:

  • 合理使用样式表
  • 选择适当的工具包
  • 注意导出质量
  • 进行性能优化
  • 监控内存使用
  • 保持代码整洁
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值