📅 系列:一起学Python | 难度:⭐⭐⭐
🔗 上期回顾:第118天:Seaborn 入门
学了十几天的 Matplotlib,你可能已经发现:API 太多太杂,每次画图都要翻文档。
折线用 plot(),散点用 scatter(),保存用 savefig() 还是 imsave()?subplot() 和 subplots() 到底有什么区别?
今天这期,我们把 Matplotlib 的核心 API 全部整理成速查表,建议收藏,随查随用。
Matplotlib 提供两种使用方式,官方推荐面向对象接口(Axes),但快速原型用 pyplot 更方便。

fig, ax = plt.subplots(),快速测试用 plt.plot()。






fig, ax = plt.subplots() 时,调用的是 Axes 方法:ax.plot() | plt.plot() | |
ax.scatter() | plt.scatter() | |
ax.bar() | plt.bar() | |
ax.set_title() | plt.title() | |
ax.set_xlabel() | plt.xlabel() | |
ax.set_ylabel() | plt.ylabel() | |
ax.set_xlim() | plt.xlim() | |
ax.set_ylim() | plt.ylim() | |
ax.set_xticks() | plt.xticks() | |
ax.set_xticklabels() | ||
ax.grid() | plt.grid() | |
ax.legend() | plt.legend() | |
ax.text() | plt.text() | |
ax.annotate() | plt.annotate() | |
ax.imshow() | plt.imshow() | |
ax.hist() | plt.hist() | |
ax.pie() | plt.pie() | |
ax.set_aspect() | ||
ax.set_facecolor() | ||
ax.spines['top'].set_visible(False) | ||
ax.twinx() | plt.twinx() | |
ax.inset_axes() |
set_(如 set_title、set_xlim),少数同名(如 plot、scatter)。fig.savefig() | fig.savefig('output.png', dpi=300) | |
fig.suptitle() | fig.suptitle('总标题', fontsize=16) | |
fig.subplots_adjust() | fig.subplots_adjust(hspace=0.3) | |
fig.set_size_inches() | fig.set_size_inches(10, 6) | |
fig.set_facecolor() | fig.set_facecolor('white') | |
fig.colorbar() | fig.colorbar(im, ax=axes) | |
fig.legend() | fig.legend(handles, labels) | |
fig.text() | fig.text(0.5, 0.95, '文字') |
plt.style.use('ggplot') # R语言风格plt.style.use('seaborn-v0_8') # Seaborn风格plt.style.use('dark_background') # 深色背景plt.style.use('fivethirtyeight') # 数据新闻风格plt.style.use('grayscale') # 灰度(适合打印)
plt.rcParams['figure.figsize'] = [10, 6] # 默认图尺寸plt.rcParams['figure.dpi'] = 100 # 默认分辨率plt.rcParams['font.size'] = 12 # 全局字体大小plt.rcParams['axes.grid'] = True # 默认显示网格plt.rcParams['axes.spines.top'] = False # 隐藏顶部边框plt.rcParams['axes.spines.right'] = False # 隐藏右侧边框plt.rcParams['savefig.dpi'] = 300 # 保存分辨率plt.rcParams['image.cmap'] = 'viridis' # 默认颜色映射
viridis | ||
hotinferno | ||
coolwarmRdBu | ||
tab10Set2 | ||
jetrainbow |
import matplotlib.pyplot as pltimport matplotlib.font_manager as fmimport numpy as npimport os# ================= 1. 字体加载(解决报错的核心) =================font_path = "simhei.ttf"if not os.path.exists(font_path):font_path = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"prop = fm.FontProperties(fname=font_path)plt.rcParams['axes.unicode_minus'] = False# 数据准备x = np.linspace(0, 10, 100)y1 = np.sin(x)y2 = np.cos(x)# ========== Figure + Axes(面向对象接口)==========fig, ax = plt.subplots(figsize=(10, 6), layout='constrained')# 绘图ax.plot(x, y1, 'o-', label='sin(x)', color='#2E86AB', markersize=4)ax.plot(x, y2, 's--', label='cos(x)', color='#E74C3C', markersize=4)# 标注峰值peak_idx = np.argmax(y1)ax.annotate(f'峰值: {y1[peak_idx]:.2f}',xy=(x[peak_idx], y1[peak_idx]),xytext=(x[peak_idx] + 2, y1[peak_idx] + 0.3),arrowprops=dict(arrowstyle='->', color='gray'),fontproperties=prop)# 文本装饰ax.set_title('正弦与余弦函数', fontproperties=prop, fontsize=16)ax.set_xlabel('X 轴(弧度)', fontproperties=prop)ax.set_ylabel('Y 轴(函数值)', fontproperties=prop)ax.legend(prop=prop)# 坐标轴控制ax.set_xlim(0, 10)ax.set_ylim(-1.5, 1.5)ax.grid(True, alpha=0.3, linestyle='--')# 隐藏边框ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)# 保存fig.savefig('runoob_demo.png', dpi=300, bbox_inches='tight')plt.show()


今天我们整理了一份 Matplotlib 的核心 API 速查手册:
✅ 两大接口:pyplot(快速) vs Axes(精细控制)
✅ pyplot 函数:按场景分类(绘图、图像、文本、轴控制、保存)
✅ Axes 方法:set_ 前缀 + 同名方法
✅ Figure 方法:全局控制(保存、总标题、布局、颜色条)
✅ 样式配置:plt.style.use() + rcParams 全局设置
✅ Colormap:viridis 首选,jet 避免
建议收藏本文,下次画图时直接Ctrl+F搜索关键词,效率翻倍。
