优先用plt.style.use('seaborn-v0_8-whitegrid')等预设样式,再设font.family为Times New Roman,保存用plt.savefig('fig.pdf', bbox_inches='tight', dpi=300)。
Matplotlib默认的plt.plot()出图确实难登论文——细线、灰背景、小字号、无衬线字体,直接暴露“没调过”。核心解法不是手动改每个参数,而是切换预设样式表+全局配置。
plt.style.use('seaborn-v0_8-whitegrid')或'ggplot',它们自带合理网格、粗细适中的线条和协调的配色;注意seaborn-v0_8-前缀需匹配你安装的seaborn版本,否则报错KeyError: 'seaborn-v0_8-whitegrid'
plt.rcParams['font.family'] = 'serif'和plt.rcParams['font.serif'] = ['Times New Roman', 'DejaVu Serif'],避免Mac/Linux下找不到字体导致回退到乱码plt.savefig('fig.pdf', bbox_inches='tight', dpi=300),PDF格式保留矢量细节,bbox_inches='tight'自动裁掉空白边距——漏掉这步常导致图例被截断plt.subplots()还是plt.subplot_mosaic()?画(a)(b)(c)三栏对比图时,手算add_subplot(2,2,1)极易错位。新版plt.subplot_mosaic()用字符串布局更直观,但老项目兼容性差;稳妥选plt.subplots()配合gridspec_kw微调。
fig, axes = plt.subplots(2, 3, figsize=(12, 6)),注意axes是二维数组,索引写axes[0, 1]而非axes[1]
gridspec:gs = fig.add_gridspec(3, 1, height_ratios=[2,1,1]),再用fig.add_subplot(gs[0])分配区域plt.tight_layout()——它对gridspec支持差,改用fig.constrained_layout = True并在创建figure时声明plt.figure(constrained_layout=True)
科研图表里plt.errorbar()和填充区域(plt.fill_between())是高频需求,但yerr传错维度、fill_between上下界顺序颠倒,会导致误差范围反向或报ValueError: x and y must have same first dimension。
plt.errorbar(x, y, yerr=y_std, capsize=3, ecolor='gray', capthick=1)中yerr若为标量则全图统一误差;若为数组,必须与y同长——常见错误是传入yerr=y_std.reshape(-1,1)导致维度不匹配plt.fill_between(x, y_lower, y_upper, alpha=0.2, color='C0'),关键点:y_lower必须严格≤y_upper,否则填充消失;若数据含nan,先用np.nan_to_num()转为0或插值,否则整段不显示errorbar必须绑定右轴:ax2.errorbar(..., ax=ax2),漏写ax参数会强行画到左轴上Matplotlib对中文和数学公式的默认支持极弱,直接写plt.xlabel('温度/℃')大概率出方块,r'$alpha$'可能报matplotlib.font_manager.UserWarning: Mathtext font is not available。
立即学习“Python免费学习笔记(深入)”;
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS'],Linux/Mac装fonts-arphic-ukai后设['AR PL UKai CN'];最关键的是加plt.rcParams['axes.unicode_minus'] = False,否则负号变方块plt.rcParams['text.usetex'] = True;但编译慢且易崩,日常推荐用plt.rcParams['mathtext.fontset'] = 'stix'——它用纯Python渲染公式,支持希腊字母和上下标,速度更快'损失函数 $L_{mathrm{total}}$',必须用r''原始字符串,且中文部分不能包在$...$里,否则解析失败真正卡住人的往往不是功能不会用,而是字体路径没生效、LaTeX缓存残留、或者保存PDF时dpi设成72还怪图模糊。动手前先跑一遍plt.matplotlib_fname()确认配置文件位置,删掉~/.matplotlib/fontlist-*.json强制重建字体缓存——这些细节不查文档根本想不到。