在使用 `matplotlib` 绘图时,如果图表中的中文(如标题、坐标轴标签、图例等)显示为方框 `□□□` 或乱码,这是因为 **matplotlib 默认使用的字体不支持中文**。
---
### ✅ 解决方案:设置支持中文的字体 + 禁用默认字体缓存
以下是一段**完整可运行的代码**,解决 matplotlib 中文显示问题:
```python
import matplotlib.pyplot as plt
import matplotlib
import sys
# --- 方法1:动态设置中文字体(推荐通用方式)---
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans', 'sans-serif'] # 支持中文的字体列表
plt.rcParams['axes.unicode_minus'] = False # 解决负号 '-' 显示为方块的问题
# --- 示例绘图 ---
plt.figure(figsize=(8, 5))
plt.plot([1, 2, 3, 4], [1, 4, 2, 3], label='数据曲线')
plt.title('这是一个包含中文的标题')
plt.xlabel('x 轴标签')
plt.ylabel('y 轴标签')
plt.legend()
plt.show()
```
---
### 🔍 详细解释
#### 1. `plt.rcParams['font.sans-serif']`
- 指定优先使用的字体族,系统会按顺序查找可用的中文字体。
- 常见中文字体名称:
- `'SimHei'`:黑体(Windows)
- `'Microsoft YaHei'`:微软雅黑(Win)
- `'FangSong'`:仿宋
- `'KaiTi'`:楷体
- `'Arial Unicode MS'`:Mac 常见支持中文的字体
- `'DejaVu Sans'`:跨平台备用字体(部分支持中文)
> 推荐写多个备选字体,提高兼容性。
#### 2. `plt.rcParams['axes.unicode_minus'] = False`
- 默认情况下,负号 `-` 可能会显示为方块。
- 设为 `False` 后,matplotlib 使用普通 ASCII 减号,避免显示异常。
---
### 🖥️ 如何查看系统可用的中文字体?
```python
from matplotlib.font_manager import FontProperties, findSystemFonts
import os
# 查找所有字体文件并打印含“黑体”、“hei”、“song”等关键词的字体
fonts = findSystemFonts()
zh_fonts = [f for f in fonts if any(key in open(f, 'rb').read().decode('utf-8', errors='ignore').lower()
for key in ['simhei', 'msyh', 'hei', 'kai', 'fangsong', 'song'])]
for font in zh_fonts:
print(font)
```
或者列出所有支持中文的字体:
```python
from matplotlib.font_manager import fmget
# 获取所有可用字体
fonts = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
# 筛选常见中文字体名
chinese_fonts = [f for f in fonts if any(k in f.lower() for k in ['hei', 'yahei', 'song', 'kai', 'fang', 'uni', 'arial unicode'])]
print("可能支持中文的字体:")
print(chinese_fonts)
```
---
### 💡 高级解决方案:永久配置 matplotlib 配置文件
如果你不想每次写代码都设置字体,可以修改 `matplotlibrc` 文件:
#### 步骤:
1. 找到配置路径:
```python
import matplotlib
print(matplotlib.matplotlib_fname()) # 输出配置文件路径,通常是 .../matplotlib/mpl-data/matplotlibrc
```
2. 编辑该文件,修改如下两行:
```
font.family : sans-serif
font.sans-serif : SimHei, Arial Unicode MS, DejaVu Sans, Bitstream Vera Sans, sans-serif
axes.unicode_minus : False
```
3. 清除字体缓存(重要!):
```bash
rm -rf ~/.matplotlib/fontList.cache
rm -rf ~/.cache/matplotlib/*
```
> 下次启动 Python 就无需再设置,自动支持中文。
---
### 🌐 跨平台兼容建议
| 平台 | 推荐字体 |
|------|----------|
| Windows | `'SimHei'`, `'Microsoft YaHei'` |
| macOS | `'Arial Unicode MS'`, `'PingFang SC'`, `'Heiti SC'` |
| Linux | 安装 `wqy-zenhei`(文泉驿正黑)或 `Noto Sans CJK` |
---