解决ax.plot中输出中文符号的问题
时间: 2023-06-26 11:06:35 浏览: 98
在使用 Matplotlib 绘制图形时,如果需要输出中文字符,需要进行以下操作:
1. 安装中文字体库
Matplotlib 默认使用的字体可能不支持中文字符,因此需要安装中文字体库。可以使用以下命令安装思源宋体字体:
```python
!apt-get install fonts-noto-cjk
```
2. 设置中文字体
在绘制图形前,需要设置中文字体,可以使用以下代码:
```python
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Noto Sans CJK TC'] # 指定中文字体
plt.rcParams['axes.unicode_minus']=False # 解决负号'-'显示为方块的问题
```
其中,`Noto Sans CJK TC` 是安装的中文字体库中的一种字体。
3. 输出中文字符
在使用 `ax.plot` 绘制图形时,可以直接在参数中使用中文字符。
完整代码示例:
```python
import matplotlib.pyplot as plt
# 设置中文字体
plt.rcParams['font.sans-serif']=['Noto Sans CJK TC']
plt.rcParams['axes.unicode_minus']=False
# 绘制图形
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel('横轴')
ax.set_ylabel('纵轴')
ax.set_title('图形标题')
plt.show()
```