matplot显示中文
时间: 2023-08-02 22:05:51 浏览: 48
要在 Matplotlib 中显示中文,需要先确保你的操作系统已经正确安装了中文字体。常见的中文字体有“SimHei”、“Microsoft YaHei”、“STHeiti”等等。以下是一些常用的方法:
1. 使用系统默认字体:在 Matplotlib 中,可以使用 rcParams 来指定字体,如下所示:
```python
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
```
2. 使用自定义字体文件:如果你有自定义的字体文件,可以通过以下方式来指定字体:
```python
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
myfont = FontProperties(fname='path/to/myfont.ttf') # 指定自定义字体文件的路径
plt.rcParams['font.family'] = myfont.get_name()
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
```
在上面的代码中,我们先通过 FontProperties 类创建了一个字体对象 myfont,然后将其设置为默认字体。
3. 在图像中指定字体:如果你只想在某个图像中使用特定的字体,可以在绘制图像时指定字体,如下所示:
```python
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
myfont = FontProperties(fname='path/to/myfont.ttf')
plt.plot(x, y)
plt.xlabel('横轴', fontproperties=myfont)
plt.ylabel('纵轴', fontproperties=myfont)
plt.title('图像标题', fontproperties=myfont)
```
在上面的代码中,我们通过 fontproperties 参数来指定字体。这样,只有这个图像中的文字才会使用指定的字体。