确保已安装 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
减少矢量图大小。fig
和 ax
。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()