Matplotlib 全面使用指南

安装与环境配置

确保已安装 Python 3.6 及以上版本。通过 pip 安装 Matplotlib:

pip install matplotlib

若需扩展功能(如 3D 绘图),可一并安装 NumPy:

pip install numpy


基础绘图

折线图示例

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y, color='blue', linestyle='--', label='Sample Line')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Basic Line Plot')
plt.legend()
plt.show()

散点图

plt.scatter(x, y, color='red', marker='o', label='Data Points')
plt.grid(True)
plt.show()


图表自定义

调整样式

  • 线宽与透明度:
    plt.plot(x, y, linewidth=2.5, alpha=0.6)
    

  • 坐标轴范围:
    plt.xlim(0, 5)
    plt.ylim(0, 40)
    

多图布局: 使用 subplots 创建多个子图:

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(x, y, color='green')
ax2.bar(['A', 'B'], [5, 10])
plt.tight_layout()
plt.show()


高级图表类型

直方图

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

3D 绘图

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter([1, 2], [3, 4], [5, 6], c='r')
plt.show()


输出与保存

保存为图片(支持 PNG、JPEG、SVG 等格式):

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


性能优化技巧

  • 大数据集时使用 rasterized=True 减少矢量图大小。
  • 避免重复创建图形对象,复用 figax
  • 对于动态数据更新,使用 FuncAnimation
    from matplotlib.animation import FuncAnimation
    def update(frame):
        line.set_ydata(np.sin(x + frame/10))
        return line,
    anim = FuncAnimation(fig, update, frames=100, interval=50)
    anim.save('animation.gif')
    


常见问题解决

中文显示乱码

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

交互模式: 启用交互式窗口(适用于 IPython/Jupyter):

plt.ion()
plt.plot(x, y)
plt.ioff()

你可能感兴趣的:(matplotlib)