Matplotlib 是 Python 中最经典、最广泛使用的二维绘图库,虽本身定位为“基础绘图引擎”而非专用于统计美化的高级库
Matplotlib 是 Python 中最经典、最广泛使用的二维绘图库,虽本身定位为“基础绘图引擎”而非专用于统计美化的高级库,但通过其高度可定制的 API,结合科学计算生态(如 NumPy、Pandas),可实现专业级的统计可视化与美化效果。常用统计美化技巧包括:
✅ 常用统计图表类型:
- 直方图(
plt.hist())+ KDE 曲线(sns.kdeplot或scipy.stats.gaussian_kde) - 箱线图(
plt.boxplot()/sns.boxplot())与小提琴图(sns.violinplot()) - 散点图 + 回归拟合线(
sns.regplot()或np.polyfit+plt.plot) - 热力图(
sns.heatmap(),常配合corr()展示相关性) - 分布图(
sns.displot()、sns.jointplot())
🎨 美化关键手段(纯 matplotlib):
- 设置样式:
plt.style.use('seaborn-v0_8')或plt.style.use('ggplot') - 自定义颜色:使用
cmap(如'viridis','coolwarm')或color=参数(支持 HEX、RGB 元组、命名色) - 字体与标签:
plt.rcParams.update({'font.sans-serif': ['SimHei', 'DejaVu Sans']})解决中文乱码;plt.title(),plt.xlabel(),plt.ylabel()配合fontsize,fontweight - 网格与布局:
ax.grid(True, alpha=0.3),plt.tight_layout()或fig.subplots_adjust() - 图例与注释:
plt.legend()、ax.annotate()添加统计信息(如均值、p值)
💡 进阶建议:
- 与 Seaborn(基于 matplotlib 封装)或 Plotly(交互式)协同使用,提升统计表达效率;
- 使用
matplotlib.pyplot.rc_context()实现局部样式控制; - 利用
mpl_toolkits.axes_grid1或sns.despine()去除冗余边框,增强简洁性。
importmatplotlib.pyplotaspltimportnumpyasnp# 示例:美化直方图 + KDEnp.random.seed(42)data=np.random.normal(0,1,1000)fig,ax=plt.subplots(figsize=(6,4))n,bins,patches=ax.hist(data,bins=30,density=True,alpha=0.7,color='steelblue',label='Histogram')# KDE 曲线kde=np.exp(-0.5*bins**2)/np.sqrt(2*np.pi)# 标准正态核近似ax.plot(bins,kde,'r-',linewidth=2,label='KDE (N(0,1))')ax.set_xlabel('Value',fontsize=12)ax.set_ylabel('Density',fontsize=12)ax.set_title('Beautiful Histogram with KDE',fontsize=14,fontweight='bold')ax.legend()ax.grid(True,alpha=0.3)plt.tight_layout()plt.show()在 matplotlib 中正确显示中文标题和坐标轴标签,关键在于解决字体缺失与编码问题。默认情况下,matplotlib 使用的字体(如 DejaVu Sans)不支持中文,会导致方块(□)或乱码。以下是完整、可靠、跨平台(Windows/macOS/Linux)的解决方案:
✅ 推荐方法(推荐优先级:1 → 2 → 3):
✅ 方法1:全局设置中文字体(推荐,一劳永逸)
importmatplotlib.pyplotaspltimportmatplotlib# 方式1a:指定系统已安装的中文字体(如微软雅黑、SimHei、Noto Sans CJK SC等)plt.rcParams['font.sans-serif']=['Microsoft YaHei','SimHei','Noto Sans CJK SC','WenQuanYi Zen Hei','DejaVu Sans']plt.rcParams['axes.unicode_minus']=False# 解决负号'−'显示为方块的问题# 方式1b:或直接设置字体路径(更精准,适用于自定义字体)# import matplotlib.font_manager as fm# zh_font = fm.FontProperties(fname='/System/Library/Fonts/PingFang.ttc') # macOS# plt.rcParams['font.family'] = 'sans-serif'# plt.rcParams['font.sans-serif'] = [zh_font.get_name()]✅ 方法2:临时上下文设置(适合单图/局部控制)
withplt.rc_context({'font.sans-serif':['SimHei','DejaVu Sans']}):plt.figure(figsize=(6,4))plt.plot([1,2,3],[1,4,2])plt.title('中文标题')plt.xlabel('横坐标')plt.ylabel('纵坐标')plt.show()✅ 方法3:为每个文本元素单独指定 FontProperties(最灵活,兼容性最强)
frommatplotlib.font_managerimportFontProperties font=FontProperties(fname='/path/to/your/chinese_font.ttf')# 如 SimHei.ttf 或 NotoSansCJKsc-Regular.otfplt.title('中文标题',fontproperties=font,fontsize=14)plt.xlabel('横坐标',fontproperties=font)plt.ylabel('纵坐标',fontproperties=font)plt.xticks(fontproperties=font)plt.yticks(fontproperties=font)🔍 验证当前可用中文字体(调试用):
importmatplotlib.font_managerasfm fonts=[f.nameforfinfm.fontManager.ttflist]print(sorted(set(fonts)))# 查看所有已识别字体名# 常见中文字体名示例:'SimHei', 'Microsoft YaHei', 'Noto Sans CJK SC', 'AR PL UKai CN'⚠️ 注意事项:
plt.rcParams['axes.unicode_minus'] = False必须设置,否则负号“−”会显示为方块;- Linux 系统可能需先安装中文字体(如
sudo apt install fonts-wqy-zenhei); - Jupyter 中若仍不生效,可尝试重启内核 + 清除缓存(
~/.matplotlib/fontlist-v330.json可删除后重生成)。
✅ 一行验证是否成功:
plt.text(0.5,0.5,'测试中文✓',fontsize=16,ha='center')plt.axis('off')plt.show()