Matplotlib 由 John D. Hunter 于 2003 年创建,灵感来源于 MATLAB 的绘图系统。作为 Python 生态中最早的可视化工具之一,它逐渐成为科学计算领域的标准可视化库。2012 年 Hunter 去世后,社区接管维护,目前最新版本已支持 Python 3.10+ 并持续集成现代可视化需求。
Matplotlib 是 Python 的 2D/3D 绘图基础库,提供类似 MATLAB 的绘图 API。核心优势在于:
pip install matplotlib
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# 创建画布和坐标轴
fig, ax = plt.subplots()
# 绘制曲线
ax.plot(x, y, label='sin(x)')
# 添加装饰元素
ax.set_title("Basic Sine Wave")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.legend()
ax.grid(True)
# 显示图形
plt.show()
代码解析:
plt.subplots()
创建 Figure 对象和 Axes 对象ax.plot()
的 label 参数用于图例文本plt.show()
触发渲染管线fig, axs = plt.subplots(2, 2, figsize=(10,8))
axs[0,0].plot(x, np.sin(x), color='r', linestyle='--')
axs[1,1].scatter(np.random.rand(50), np.random.rand(50))
plt.style.use('ggplot') # 使用预置主题
ax.plot(x, y,
linewidth=2,
marker='o',
markersize=8,
markerfacecolor='yellow',
markeredgecolor='black')
# 等高线图
X, Y = np.meshgrid(np.linspace(-3,3,100), np.linspace(-3,3,100))
Z = np.sin(X**2 + Y**2)
ax.contourf(X, Y, Z, levels=20, cmap='coolwarm')
# 3D 绘图
from mpl_toolkits.mplot3d import Axes3D
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, rstride=5, cstride=5)
from matplotlib.widgets import Slider
ax_slider = plt.axes([0.2, 0.05, 0.6, 0.03])
freq_slider = Slider(ax_slider, 'Frequency', 1, 10, valinit=1)
def update(val):
line.set_ydata(np.sin(freq_slider.val * x))
fig.canvas.draw_idle()
freq_slider.on_changed(update)
from matplotlib.animation import FuncAnimation
def animate(frame):
line.set_ydata(np.sin(x + frame/10))
return line,
ani = FuncAnimation(fig, animate, frames=100, interval=50)
import seaborn as sns
tips = sns.load_dataset("tips")
sns.violinplot(x="day", y="total_bill", data=tips)
plt.title("Seaborn + Matplotlib Integration")
动态股票K线图实现
import mplfinance as mpf # Matplotlib扩展库
# 获取股票数据
data = pd.read_csv('stock.csv', index_col=0, parse_dates=True)
# 配置样式参数
style = mpf.make_marketcolors(up='g', down='r',
edge={'up':'g','down':'r'},
wick={'up':'g','down':'r'},
volume={'up':'g','down':'r'})
mpf_style = mpf.make_mpf_style(marketcolors=style)
# 绘制专业K线图
mpf.plot(data, type='candle',
style=mpf_style,
volume=True,
title='Stock Price Analysis',
ylabel='Price (USD)',
ylabel_lower='Volume',
figratio=(12,6),
mav=(5,20))
实现要点:
plt.rcParams['font.sans-serif'] = ['SimHei']
支持中文rasterized=True
参数启用栅格化Matplotlib 作为 Python 可视化的基石,其学习曲线呈现先陡后缓的特点。尽管新兴库(如 Plotly、Bokeh)在交互性方面表现突出,但 Matplotlib 在定制化程度和底层控制方面仍具有不可替代性。建议的学习路径:
Matplotlib的面向对象设计是其强大灵活性的基础。要真正掌握高级绘图技巧,必须深入理解其对象层级关系。
Figure对象:相当于物理画布,可包含多个Axes对象
fig = plt.figure(figsize=(8,6), dpi=100, facecolor='#f0f0f0')
fig.suptitle('Master Figure Control') # 总标题
重要属性:
fig.axes
: 包含的所有Axes对象fig.patch
: 背景矩形对象fig.subplots_adjust()
: 调整子图间距Axes对象:真正的绘图区域,每个Axes包含:
ax = fig.add_subplot(111, projection='polar') # 创建极坐标轴
ax.set_theta_offset(np.pi/2) # 调整角度坐标系
Artist对象:所有可见元素的基类,包括:
line = ax.plot(x, y)[0] # 获取Line2D实例
line.set_marker('D') # 直接操作图形元素
Matplotlib提供四种坐标系统:
转换示例:
# 在数据坐标(5,0.8)处添加文字
ax.text(5, 0.8, 'Critical Point',
transform=ax.transData)
# 在画布右上角添加logo
fig.text(0.95, 0.9, '© DataLab',
ha='right',
transform=fig.transFigure)
小提琴图与箱线图组合:
fig, ax = plt.subplots()
vp = ax.violinplot(dataset, showmedians=True)
bp = ax.boxplot(dataset, positions=np.arange(1,5),
widths=0.15, patch_artist=True)
# 样式调整
for body in vp['bodies']:
body.set_facecolor('skyblue')
body.set_alpha(0.5)
for box in bp['boxes']:
box.set_facecolor('orange')
热力图增强:
import matplotlib.colors as mcolors
# 自定义颜色映射
cmap = mcolors.LinearSegmentedColormap.from_list('custom', ['#2E86C1','#F4D03F','#CB4335'])
heatmap = ax.imshow(data, cmap=cmap, norm=mcolors.LogNorm())
fig.colorbar(heatmap, ax=ax, extend='both')
import cartopy.crs as ccrs
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111, projection=ccrs.PlateCarree())
ax.coastlines(resolution='50m')
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
ax.gridlines(crs=ccrs.PlateCarree(), linewidth=0.3)
# 绘制等温线
cs = ax.contourf(lon, lat, temp, 15,
transform=ccrs.PlateCarree())
fig.colorbar(cs, shrink=0.5)
# 使用线条简化算法
from matplotlib.path import Path
from matplotlib.markers import MarkerStyle
path = Path(np.random.rand(1e6, 2))
marker = MarkerStyle('o').get_path()
collection = PathCollection([marker], offsets=path.vertices)
ax.add_collection(collection)
# 启用栅格化
ax.plot(large_x, large_y, rasterized=True)
# 及时清理不需要的对象
fig.clf() # 清理Figure
plt.close('all') # 关闭所有窗口
del ax, fig # 释放内存
# 复用绘图对象
line.set_xdata(new_x) # 更新数据而非重新绘制
line.set_ydata(new_y)
ax.relim() # 重设坐标范围
ax.autoscale_view()
from matplotlib.backend_bases import NavigationToolbar2
class CustomToolbar(NavigationToolbar2):
toolitems = [t for t in NavigationToolbar2.toolitems if
t[0] in ('Home', 'Pan', 'Zoom')]
toolitems.append(('Save CSV', 'Export data', 'filesave', 'save_csv'))
def save_csv(self, *args):
# 实现数据导出逻辑
pass
fig.canvas.toolbar = CustomToolbar(fig.canvas)
def on_motion(event):
if event.inaxes:
ax = event.inaxes
x, y = event.xdata, event.ydata
cursor_text.set_text(f'({x:.2f}, {y:.2f})')
fig.canvas.draw_idle()
fig.canvas.mpl_connect('motion_notify_event', on_motion)
plt.rcParams.update({
"text.usetex": True,
"font.family": "serif",
"font.serif": ["Times New Roman"],
})
ax.set_xlabel(r'$\sqrt{(n_\text{c}(t|{T}))}$',
fontsize=14)
fig.savefig('publication_quality.pdf',
bbox_inches='tight',
pad_inches=0.1,
dpi=1200,
metadata={'Creator': 'My Research Lab',
'Title': 'Fig.3 Experimental Results'})
# 结合Pandas数据操作
df.plot(kind='hexbin', x='A', y='B', gridsize=20,
cmap='viridis', ax=ax)
# 使用Seaborn增强统计绘图
import seaborn as sns
sns.regplot(x='total_bill', y='tip', data=tips,
scatter_kws={'alpha':0.5},
line_kws={'color':'red'},
ax=ax[1])
通过系统掌握Matplotlib的核心机制与扩展应用,开发者可以应对从简单数据探索到复杂科学可视化的全方位需求。关键学习路径包括:
建议实践策略:
Matplotlib作为历经20年发展的可视化基石,其深度与广度仍将持续演进,值得数据工作者长期投入学习与实践。
让AI成为我们的得力助手:
点击链接:《用Cursor玩转AI辅助编程——不写代码也能做软件开发》