使用的操作系统为Windows,比如用下面这段代码,中文是无法正确显示的:
from matplotlib import pyplot as plt
import numpy as np
import random
x = range(0,120)
y = [random.randint(20, 35) for i in range(120)]
plt.figure(figsize=(20, 8), dpi=80)
plt.plot(x, y)
plt.xlabel("X轴是")
plt.show()
要让汉字正确显示,推荐使用如下的方法:
from matplotlib import font_manager
#设置使用的字体,此处使用的是微软雅黑
my_font = font_manager.FontProperties(fname='C:\Windows\Fonts\MSYH.TTC')
#设置引用的方法
plt.xlabel("X轴是", fontproperties = my_font)
完整代码及显示结果如下:
from matplotlib import pyplot as plt
from matplotlib import font_manager
import numpy as np
import random
x = range(0,120)
y = [random.randint(20, 35) for i in range(120)]
#设置使用的字体,此处使用的是微软雅黑
my_font = font_manager.FontProperties(fname='C:\Windows\Fonts\MSYH.TTC')
plt.figure(figsize=(20, 8), dpi=80)
plt.plot(x, y)
#设置引用格式
plt.xlabel("X轴是", fontproperties = my_font)
plt.show()