Python的matplotlib如何将标签设置成中文
时间: 2023-05-31 11:04:42 浏览: 85
要将matplotlib的标签设置为中文,需要使用以下步骤:
1. 安装中文字体:在matplotlib中使用中文,需要先安装中文字体。可以使用系统自带的中文字体,或者下载其他中文字体。将字体文件放在系统字体目录下(如Windows系统下的C:\Windows\Fonts目录)。
2. 导入字体:将中文字体导入到matplotlib中。可以使用以下代码导入字体:
```python
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\SimSun.ttc", size=14) # 指定中文字体文件和字号
```
3. 设置标签:使用上面导入的字体,设置标签的中文文字。例如:
```python
plt.xlabel('横轴', fontproperties=font)
plt.ylabel('纵轴', fontproperties=font)
plt.title('标题', fontproperties=font)
```
完整的示例代码如下:
```python
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\SimSun.ttc", size=14)
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.xlabel('横轴', fontproperties=font)
plt.ylabel('纵轴', fontproperties=font)
plt.title('标题', fontproperties=font)
plt.show()
```
运行上面的代码,即可在matplotlib中将标签设置为中文。