# UnicodeEncodeError: 'locale'编解码器无法在位置0编码字符'\u2014'：编码错误

- **ID:** `python/matplotlib-unicode-title-error`
- **领域:** python
- **类别:** encoding_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

Matplotlib的默认后端尝试使用系统区域设置编码对Unicode字符（例如长破折号）进行编码，但该编码可能不支持这些字符，尤其是在非UTF-8区域设置下。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |

## 解决方案

1. **Set the environment variable PYTHONIOENCODING to utf-8 before importing matplotlib** (85% 成功率)
   ```
   import os; os.environ['PYTHONIOENCODING'] = 'utf-8'; import matplotlib.pyplot as plt
   ```
2. **Use a non-interactive backend like 'Agg'** (90% 成功率)
   ```
   import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt
   ```

## 无效尝试

- **Setting plt.rcParams['font.sans-serif'] to a different font without addressing locale encoding** — Font change does not affect the encoding step; the error persists because the backend still uses locale for output. (80% 失败率)
- **Adding # -*- coding: utf-8 -*- to the script** — This only affects source file encoding, not runtime output encoding; the locale issue remains. (90% 失败率)
