你遇到的错误:
```
findfont: Font family 'WenQuanYi Micro Hei' not found.
findfont: Font family 'Heiti TC' not found.
```
是因为 `matplotlib` 在你的系统中**找不到指定的中文字体**,导致中文显示为方框或报错。这是 Python 绘图中最常见的中文乱码问题。
---
### ✅ 解决方案:动态检测并使用系统已安装的中文字体
我们可以通过以下步骤解决这个问题:
1. **列出当前系统中所有可用的字体**
2. **筛选出支持中文的常见字体(如 SimHei、Microsoft YaHei 等)**
3. **设置 matplotlib 使用其中一个可用字体**
---
### ✅ 正确代码:自动选择系统中可用中文字体
```python
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import networkx as nx
from matplotlib.patches import Rectangle
# ----------------------------
# 第一步:查找系统中可用的中文字体
# ----------------------------
def get_chinese_font():
# 获取所有可用字体名称
fonts = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
# 常见中文字体名(不区分大小写)
chinese_fonts = [
'SimHei', # 黑体 - Windows 常见
'Microsoft YaHei', # 微软雅黑 - Windows 10+
'FangSong', # 仿宋
'KaiTi', # 楷体
'PingFang SC', # 苹方 - macOS
'Hiragino Sans GB', # macOS 常见
'WenQuanYi Micro Hei', # Linux 常见
'Noto Sans CJK', # Google 开源字体(多平台)
'Source Han Sans', # 思源黑体
]
# 查找第一个匹配的字体
for font in chinese_fonts:
if font in fonts:
return font
# 如果都没找到,尝试模糊匹配
for font in fonts:
if any(kw in font.lower() for kw in ['hei', 'yahei', 'kai', 'song', 'fang', 'wenquan', 'ping', 'noto']):
return font
return None
# 尝试获取中文字体
chinese_font = get_chinese_font()
if chinese_font is None:
print("⚠️ 未找到可用中文字体,将使用默认字体(可能显示乱码)")
else:
print(f"✅ 找到中文字体: {chinese_font}")
plt.rcParams['font.sans-serif'] = [chinese_font] # 设置中文字体
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
# ----------------------------
# 第二步:绘制技术路径图
# ----------------------------
G = nx.DiGraph()
# 节点列表(带标签)
nodes = [
"A: 文献梳理与概念界定",
"B: 理论框架构建:\n文旅融合对高质量发展的\n直接影响机制",
"C: 指标体系构建:\n文旅融合指数+\n旅游高质量发展指数",
"D: 数据收集:\n西部12省面板数据\n(2014–2024)",
"E: 实证分析:\n面板回归模型\n(固定效应)",
"F: 稳健性检验",
"G: 异质性检验",
"I: 结论与政策建议"
]
# 添加节点和边
G.add_nodes_from(nodes)
edges = [(nodes[i], nodes[i+1]) for i in range(len(nodes)-1)]
G.add_edges_from(edges)
# 垂直布局位置
pos = {}
y_pos = np.linspace(0, -len(nodes), len(nodes)) # 从上到下
for idx, node in enumerate(nodes):
pos[node] = (0, y_pos[idx])
# 创建图形
fig, ax = plt.subplots(figsize=(14, 10))
ax.set_xlim(-1, 1)
ax.set_ylim(y_pos[-1] - 0.5, 0.5)
ax.axis('off')
# 绘制边(箭头)
for i in range(len(nodes) - 1):
start = pos[nodes[i]]
end = pos[nodes[i+1]]
ax.annotate('', xy=end, xytext=start,
arrowprops=dict(arrowstyle='->', color='gray', lw=2, shrinkA=20, shrinkB=20),
)
# 绘制节点(用矩形 + 文本模拟)
node_width = 0.8
node_height = 0.35
for node in nodes:
x, y = pos[node]
# 绘制背景矩形
rect = Rectangle((x - node_width/2, y - node_height/2), node_width, node_height,
linewidth=2, edgecolor='darkblue', facecolor='lightcyan', alpha=0.9)
ax.add_patch(rect)
# 提取文本内容(去掉 A: 这样的前缀)
label = node.split(":", 1)[1].strip()
ax.text(x, y, label, fontsize=12, ha='center', va='center',
fontweight='normal', wrap=True, linespacing=1.2)
# 标题(可选)
plt.title("研究技术路径图:文旅融合对高质量发展的影响", fontsize=16, pad=20)
# 保存高清图像
plt.savefig("technical_pathway_chinese.png", dpi=300, bbox_inches='tight', facecolor='white')
plt.show()
```
---
### 🔍 关键说明:
| 功能 | 说明 |
|------|------|
| `get_chinese_font()` 函数 | 自动扫描系统字体,优先选择常见中文字体 |
| `plt.rcParams['font.sans-serif']` | 设置全局字体,避免硬编码不存在的字体 |
| `Rectangle` 补丁 | 模拟流程图中的圆角矩形框(比默认节点更美观) |
| `annotate` 绘制箭头 | 更灵活控制箭头起点/终点(避开节点边界) |
| `bbox_inches='tight'` | 紧凑裁剪,防止文字被截断 |
---
### 💡 如果仍然失败?手动解决方案:
#### ✅ 方法一:Windows 用户推荐
直接使用:
```python
plt.rcParams['font.sans-serif'] = ['SimHei'] # 或 'Microsoft YaHei'
```
#### ✅ 方法二:Mac 用户
```python
plt.rcParams['font.sans-serif'] = ['PingFang SC', 'Hiragino Sans GB']
```
#### ✅ 方法三:Linux 用户(Ubuntu/Debian)
安装文泉驿微米黑:
```bash
sudo apt install fonts-wqy-microhei
```
然后在 Python 中设置:
```python
plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei']
```
---
### ✅ 验证当前系统有哪些字体可用
你可以运行下面这段代码查看所有字体:
```python
import matplotlib.font_manager as fm
fonts = sorted([f.name for f in fm.fontManager.ttflist])
print("\n".join(fonts))
```
然后从中找一个包含 “Hei”、“YaHei”、“Kai”、“Fang”、“Ping” 的名字即可使用。
---
###